精华内容
下载资源
问答
  • Feign文件上传

    2018-10-28 00:23:42
    Feign文件上传 1. 在自己的文件上传服务中引入feign 提供的依赖 <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form&...

    Feign文件上传

    1. 在自己的文件上传服务中引入feign 提供的依赖

            <dependency>
               <groupId>io.github.openfeign.form</groupId>
                <artifactId>feign-form</artifactId>
                <version>3.0.3</version>
            </dependency>
            <dependency>
                <groupId>io.github.openfeign.form</groupId>
                <artifactId>feign-form-spring</artifactId>
                <version>3.0.3</version>
            </dependency>
    

    2.编写文件上传controller

    @RestController
    @RequestMapping
    @Slf4j
    public class StorageController {
    
        @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        @ResponseBody
        public String upload(@RequestParam("file") MultipartFile file) {
    
            return "";
        }
    }
    

    3.编写供其他服务调用的feignClient

    需要自定义配置feign 的encoder来解码multipartFile提交

    在FeignClientsConfiguration第74行可知feign默认的encoder配置是 SpringEncoder

       @Bean
    	@ConditionalOnMissingBean
    	public Encoder feignEncoder() {
    		return new SpringEncoder(this.messageConverters);
    	}
    
    
    (1).第一种配置方式
    @FeignClient(value = "ResourceService",
            path = "/resource/",
            configuration = ResourceClient.MultipartConfig.class)
    public interface ResourceClient {
        @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        Resource upload(@RequestPart("file") MultipartFile file);
    
        class MultipartConfig {
            @Bean
            public Encoder feignFormEncoder() {
                return new SpringFormEncoder();
            }
        }
    }
    

    使用@FeignClient的configuration来配置当前client的encoder
    注意不要在此配置类上添加@configruation,否则会影响全局的encoder配置

    这样的话只会修改当前Client的默认的encoder

    (2).第二种配置方式

    直接修改全局的Encoder

    @FeignClient(value = "ResourceService",
            path = "/resource/")
    public interface ResourceClient {
        @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        Resource upload(@RequestPart("file") MultipartFile file);
    }
    
    @Configruation
    public  class MultipartConfig {
            @Bean
            public Encoder feignFormEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
                return new SpringFormEncoder(new SpringEncoder(messageConverters));
            }
    }
    

    如果直接将默认的全局SpringEncoder替换为SpringFormEncoder的话,普通的请求可能会报xxx is not a type supported by this encoder 的异常。

    查看SpringFormEncoder的源码可知SpringFormEncoder.encode()方法判断bodyType是不是multipartFile,不是的话就直接调用默认的Encode处理
    SpringFormEncoder的encode方法
    默认的Encoder.Default.encode()只会判断bodyType是否是 String还是byte[] 否则就会报xxx is not a type supported by this encoder 的异常。
    Encoder.Default.encode
    所以在将全局的Encoder替换为SpringFormEncoder时将SpringFormEncoder的默认的encoder设置为SpringEncoder

    展开全文
  • 通过Feign 扩展 可以实现Feign 单个文件和多个文件的上传,示例代码中演示了单个文件上传,多个文件上参考博客自己实现即可。文章地址:https://blog.csdn.net/AaronSimon/article/details/82710938
  • 主要为大家详细介绍了SpringCloud使用Feign文件上传、下载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • SpringBoot Feign文件上传

    2020-08-11 22:19:58
    Feign 文件上传,与普通的远程调用会有所不同,注意了。 客户端 <feign-form.version>3.0.3</feign-form.version> <!-- 文件上传 --> <dependency> <groupId>io.github.openfeign....

    写在前面

    Feign 文件上传,与普通的Feign远程调用会有所不同,使用的时候需要注意。

    客户端

    <feign-form.version>3.0.3</feign-form.version>
    <!-- 文件上传 -->
    <dependency>
        <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form</artifactId>
        <version>${feign-form.version}</version>
    </dependency>
    <dependency>
        <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form-spring</artifactId>
        <version>${feign-form.version}</version>
    </dependency>
    
    import feign.codec.Encoder;
    import feign.form.spring.SpringFormEncoder;
    import org.springframework.beans.factory.ObjectFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
    import org.springframework.cloud.openfeign.support.SpringEncoder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.context.annotation.Scope;
    
    /**
     * @author :GuangxiZhong
     * @date :Created in 2020/8/11 21:34
     * @description:Feign解决文件上传问题
     * @modified By:
     * @version: 1.0
     */
    @Configuration
    public class FeignEncoderConfig {
        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;
    
        @Bean
        @Primary
        @Scope("prototype")
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
    }
    
    @FeignClient(value = CloudServiceNameConstants.IM)
    public interface ImService {
    	@RequestMapping(value = "/biz/imController/upload/image", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    	Map<String, Object> uploadImage(@RequestPart("file") MultipartFile file, @RequestParam("type") int type);
    }
    

    服务端

    /**
     * 上传图片和文件
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "upload/image", method = RequestMethod.POST)
    public Map<String, Object> uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request, int type) {
        try {
            String name = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            FileUtil.saveFile("/local/image/", name, file.getBytes());
        } catch (Exception e) {
            log.error("上传图片或异常", e);
            return null;
        }
    }
    
    
    import com.alibaba.fastjson.util.IOUtils;
    import com.google.common.base.Preconditions;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.ArrayUtils;
    import org.apache.commons.lang3.StringUtils;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.Arrays;
    import java.util.zip.CRC32;
    import java.util.zip.CheckedOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    /**
     * @author MrBird
     */
    @Slf4j
    public class FileUtil {
    
        private static final int BUFFER = 1024 * 8;
    
        /**
         * 允许下载的文件类型,根据需求自己添加(小写)
         */
        public static final String[] VALID_FILE_TYPE = {"xlsx", "zip"};
    
        /**
         * 压缩文件或目录
         *
         * @param fromPath 待压缩文件或路径
         * @param toPath   压缩文件,如 xx.zip
         */
        public static void compress(String fromPath, String toPath) throws IOException {
            File fromFile = new File(fromPath);
            File toFile = new File(toPath);
            if (!fromFile.exists()) {
                throw new FileNotFoundException(fromPath + "不存在!");
            }
            try (
                    FileOutputStream outputStream = new FileOutputStream(toFile);
                    CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
                    ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream)
            ) {
                String baseDir = "";
                compress(fromFile, zipOutputStream, baseDir);
            }
        }
    
        /**
         * 文件下载
         *
         * @param filePath 待下载文件路径
         * @param fileName 下载文件名称
         * @param delete   下载后是否删除源文件
         * @param response HttpServletResponse
         * @throws Exception Exception
         */
        public static void download(String filePath, String fileName, Boolean delete, HttpServletResponse response) throws Exception {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new Exception("文件未找到");
            }
    
            String fileType = getFileType(file);
            if (!fileTypeIsValid(fileType)) {
                throw new Exception("暂不支持该类型文件下载");
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "utf-8"));
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            try (InputStream inputStream = new FileInputStream(file); OutputStream os = response.getOutputStream()) {
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }
            } finally {
                if (delete) {
                    delete(filePath);
                }
            }
        }
    
        /**
         * 递归删除文件或目录
         *
         * @param filePath 文件或目录
         */
        public static void delete(String filePath) {
            File file = new File(filePath);
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null) {
                    Arrays.stream(files).forEach(f -> delete(f.getPath()));
                }
            }
            try {
                Files.delete(Paths.get(filePath));
            } catch (IOException e) {
                log.error("删除失败", e);
            }
        }
    
        /**
         * 获取文件类型
         *
         * @param file 文件
         * @return 文件类型
         * @throws Exception Exception
         */
        private static String getFileType(File file) throws Exception {
            Preconditions.checkNotNull(file);
            if (file.isDirectory()) {
                throw new Exception("file不是文件");
            }
            String fileName = file.getName();
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        }
    
    
        /**
         * 校验文件类型是否是允许下载的类型
         * (出于安全考虑:https://github.com/wuyouzhuguli/FEBS-Shiro/issues/40)
         *
         * @param fileType fileType
         * @return Boolean
         */
        private static Boolean fileTypeIsValid(String fileType) {
            Preconditions.checkNotNull(fileType);
            fileType = StringUtils.lowerCase(fileType);
            return ArrayUtils.contains(VALID_FILE_TYPE, fileType);
        }
    
        private static void compress(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
            if (file.isDirectory()) {
                compressDirectory(file, zipOut, baseDir);
            } else {
                compressFile(file, zipOut, baseDir);
            }
        }
    
        private static void compressDirectory(File dir, ZipOutputStream zipOut, String baseDir) throws IOException {
            File[] files = dir.listFiles();
            if (files != null && ArrayUtils.isNotEmpty(files)) {
                for (File file : files) {
                    compress(file, zipOut, baseDir + dir.getName() + "/");
                }
            }
        }
    
        private static void compressFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
            if (!file.exists()) {
                return;
            }
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
                ZipEntry entry = new ZipEntry(baseDir + file.getName());
                zipOut.putNextEntry(entry);
                int count;
                byte[] data = new byte[BUFFER];
                while ((count = bis.read(data, 0, BUFFER)) != -1) {
                    zipOut.write(data, 0, count);
                }
            }
        }
    
        public static String saveFile(String path,String fileName, byte[] bytes) throws Exception {
            FileOutputStream fileOutputStream = null;
            BufferedOutputStream bufferedOutputStream = null;
            try {
                if (!new File(path).exists()) {
                    new File(path).mkdirs();
                }
                String filePath = path + fileName;
                fileOutputStream = new FileOutputStream(new File(filePath));
                bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                bufferedOutputStream.write(bytes);
                return fileName;
            } finally {
                IOUtils.close(bufferedOutputStream);
                IOUtils.close(fileOutputStream);
            }
        }
    }
    
    展开全文
  • springcloud中feign文件上传、下载

    万次阅读 2018-09-21 17:50:07
    文件上传、下载也是实际项目中会遇到的场景,本篇我们介绍下spring...一、Feign文件上传 服务提供方java代码: /** * 文件上传 * @param file 文件 * @param fileType * @return */ @RequestMapping(met...

    文件上传、下载也是实际项目中会遇到的场景,本篇我们介绍下springcloud中如何使用feign进行文件上传与下载 。 

    还是使用feign 进行http的调用。

    一、Feign文件上传

    服务提供方java代码:

    /**
     * 文件上传
     * @param file 文件 
     * @param fileType   
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/uploadFile",
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String uploadFile(@RequestPart(value = "file") MultipartFile file,
            @RequestParam(value = "fileType") String fileType,
            HttpServletRequest request,HttpServletResponse response) {
        System.out.println("fileType:"+fileType);
        long size= file.getSize();
        String contentType= file.getContentType();
        String name = file.getName();
        String orgFilename= file.getOriginalFilename(); 
        System.out.println("size:"+size);
        System.out.println("contentType:"+contentType);
        System.out.println("name:"+name);
        System.out.println("orgFilename:"+orgFilename);
         
        String suffix = orgFilename.substring(orgFilename.lastIndexOf("."));//后缀
          
        String uuid =UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
         
        File dest =   new File("f:/b13/"+uuid+suffix);
         try {
            file.transferTo(dest);
             
            return dest.getCanonicalPath();//文件的绝对路径
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
         return "failure";
    }

    服务提供方Feign api接口:

    @RequestMapping(method = RequestMethod.POST, value = "/uploadFile",
                produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
                consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        public String uploadFile(@RequestPart(value = "file") MultipartFile file, @RequestParam(value = "fileType") String fileType);
    
    

    服务消费方:

    pom.xml 

    <!--  引入文件feign文件上传依赖 -->
        <dependency>
           <groupId>io.github.openfeign.form</groupId>
           <artifactId>feign-form</artifactId>
           <version>3.0.3</version>
         </dependency>
        <dependency>
           <groupId>io.github.openfeign.form</groupId>
           <artifactId>feign-form-spring</artifactId>
           <version>3.0.3</version>
        </dependency>

    java代码:

       @Autowired
    private UserProControllerApi   userProControllerApi;
     
     
     @ResponseBody
     @RequestMapping("/user_uploadFile")
     public Object  user_uploadFile(HttpServletRequest request,HttpServletResponse response,
             @RequestPart(value = "file") MultipartFile file, String fileType) {
       
           System.out.println(fileType);
           
          return userProControllerApi.uploadFile(file, fileType);
     }

    MultipartSupportConfig.java

    @Configuration
    public class MultipartSupportConfig {
         
         
        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;
         
     
        @Bean
        @Primary
        @Scope("prototype")
        public Encoder feignEncoder() {
              return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
         
         @Bean
          public feign.Logger.Level multipartLoggerLevel() {
              return feign.Logger.Level.FULL;
          }
     
    }

    二、Feign文件下载

    服务提供方java代码:

    /**
          * 文件(二进制数据)下载
          * @param fileType 文件类型
          * @return
          */
         @RequestMapping("/downloadFile")
         public   ResponseEntity<byte[]> downloadFile(String fileType,HttpServletRequest request ){
              
              System.out.println(request.getParameter("fileType"));
              System.out.println("参数fileType: "+fileType);
              
             HttpHeaders headers = new HttpHeaders();
             ResponseEntity<byte[]> entity = null;
             InputStream in=null;
              try {
               in=new FileInputStream(new File("d:/myImg/001.png"));
                 
               byte[] bytes = new byte[in.available()];
                 
               String imageName="001.png";
                
               //处理IE下载文件的中文名称乱码的问题
               String header = request.getHeader("User-Agent").toUpperCase();
               if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                   imageName = URLEncoder.encode(imageName, "utf-8");
                   imageName = imageName.replace("+", "%20");    //IE下载文件名空格变+号问题
               } else {
                   imageName = new String(imageName.getBytes(), "iso-8859-1");
               }
                 
               in.read(bytes);
                
               headers.add("Content-Disposition", "attachment;filename="+imageName);
                 
               entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
                
           } catch (Exception e) {
               e.printStackTrace();
           }finally {
               if(in!=null) {
                   try {
                       in.close();
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           }
             
              return entity;
         }

    服务提供方feign api接口 

    @RequestMapping("/downloadFile")
          public   ResponseEntity<byte[]> downloadFile(@RequestParam(value = "fileType")  String fileType
                  );

    服务消费方

    @ResponseBody
         @RequestMapping("/user_downloadFile")
         public Object  user_downloadFile(HttpServletRequest request,HttpServletResponse response,
                  String fileType) {
             ResponseEntity<byte[]>  entity = userProControllerApi.downloadFile(fileType);
             System.out.println( entity.getStatusCode());
             return entity ;
         }

     

    注:实际项目中如果上传的文件太大,可以使用ftp服务器保存上传的文件,直接在controller端调用ftp接口即可。

    如果下载的文件太大,则调用service端接口可返回一个ftp文件资源路径,然后在controller端调用ftp下载文件即可。

     ~~

     

     

     

    展开全文
  • 一、 Feign文件上传服务提供者 二、 Feign文件下载服务提供者 三、 消费者调用 文件上传、下载也是实际项目中会遇到的场景,本篇我们介绍下SpringCloud中如何使用Feign进行文件上传与下载 一、 Feign文件上传...

    目录

    一、 Feign文件上传服务提供者

    二、 Feign文件下载服务提供者

    三、 消费者调用


    文件上传、下载也是实际项目中会遇到的场景,本篇我们介绍下SpringCloud中如何使用Feign进行文件上传与下载

     

    一、 Feign文件上传服务提供者

    1. pom.xml 依赖jar

    <!--  引入文件feign文件上传依赖 -->
        <dependency>
           <groupId>io.github.openfeign.form</groupId>
           <artifactId>feign-form</artifactId>
           <version>3.0.3</version>
         </dependency>
        <dependency>
           <groupId>io.github.openfeign.form</groupId>
           <artifactId>feign-form-spring</artifactId>
           <version>3.0.3</version>
        </dependency>

    2. Feign 文件上传配置文件

    
    @Configuration
    public class FeignMultipartSupportConfig {
    
        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;
    
    
        @Bean
        @Primary
        @Scope("prototype")
        public Encoder feignEncoder() {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
    
        @Bean
        public feign.Logger.Level multipartLoggerLevel() {
            return feign.Logger.Level.FULL;
        }
    
    }

    3. FileUploadFeign中Api提供

    
    @FeignClient(
            contextId = "FileUploadFeign",
            name = "user-service",
            configuration = FeignMultipartSupportConfig.class
    
    )
    public interface FileUploadFeign {
    
        /**
         * 单个文件上传
         * @RequestPart:文件传输
         * @param file 文件
         * @param type 目录
         * @date: 2021/3/26 9:27
         * @return: com.zlp.dto.UploadResp
         */
        @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        UploadResp uploadFile(@RequestPart(value = "file") MultipartFile file,
                              @RequestParam(value = "type") String type);
    
    
        /**
         * 多个文件上传
         * @RequestPart:文件传输
         * @param files 文件
         * @param type 目录
         * @date: 2021/3/26 9:27
         * @return: com.zlp.dto.UploadResp
         */
        @PostMapping(value = "/uploadFiles", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        List<UploadResp> uploadFiles(@RequestPart(value = "files") MultipartFile[] files, @RequestParam(value = "type") String type);
    
    }

    4. FileUploadFeignImpl中Api实现类

    
    @RestController
    @Slf4j(topic = "FileUploadFeignImpl")
    @Api(value = "UserFeign", tags = "用户Feign")
    public class FileUploadFeignImpl implements FileUploadFeign {
    
        @Resource
        private OssTemplate ossTemplate;
        //目前所有文件都存放在该命名空间下
        private final static String BucketName = "greenvalley";
    
        @Override
        public UploadResp uploadFile(MultipartFile file, String type) {
    
            log.info("uploadFile.req type={}",type);
            UploadResp uploadResp = new UploadResp();
            String originalFilename = file.getOriginalFilename();
            uploadResp.setFileName(originalFilename);
            String filePath = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(originalFilename);
            if (!StringUtils.isEmpty(type)) {
                filePath = type + StrUtil.SLASH + filePath;
            }
            try {
                ossTemplate.putObject(BucketName, filePath, file.getInputStream());
                String fileUrl = ConstantsUtil.HTTP_PREFIX + BucketName + StrUtil.DOT + ConstantsUtil.DOMAIN + StrUtil.SLASH + filePath;
                uploadResp.setFileUrl(fileUrl);
                return uploadResp;
            } catch (Exception e) {
                log.error("上传失败", e);
            }
            return null;
        }
    
        @Override
        public List<UploadResp> uploadFiles(MultipartFile[] files, String type) {
    
            List<UploadResp> uploadRespList = new ArrayList<>();
            for (MultipartFile file : files) {
                uploadRespList.add(this.uploadFile(file,type));
            }
            return uploadRespList;
        }
    }

    二、 Feign文件下载服务提供者

    1. FileDownFeign中Api提供

    @FeignClient(
            contextId = "fileDownFeign",
            name = "file-web"
    
    )
    public interface FileDownFeign {
    
    
    
        @PostMapping(value = "/v1/getObject",consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE)
        ResponseEntity<byte[]> getObject(String downFileUrl);
    
        @GetMapping("/downloadFile")
        ResponseEntity<byte[]> downloadFile(@RequestParam(value = "fileType")  String fileType) ;
    
    }

    2. FileDownFeignImpl中Api实现类

    
    @RestController
    @Slf4j(topic = "FileDownFeignImpl")
    @Api(value = "FileDownFeign", tags = "文件下载模块")
    public class FileDownFeignImpl implements FileDownFeign {
    
    
        @Resource
        private OssTemplate ossTemplate;
    
        @Override
        @PostMapping(value = "/v1/getObject")
        public ResponseEntity<byte[]> getObject(String downFileUrl) {
    
            downFileUrl = "test/2ca1024b993a41eab9b88de67fc8c294.mp4";
            OSSObject ossObject = ossTemplate.getObject(downFileUrl);
            HttpHeaders headers = new HttpHeaders();
            ResponseEntity<byte[]> entity = null;
            BufferedInputStream bis;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[10240];
            try {
                bis = new BufferedInputStream(ossObject.getObjectContent());
                while (true) {
                    int len = bis.read(buf);
                    if (len < 0) {
                        break;
                    }
                    bos.write(buf, 0, len);
                }
                //将输出流转为字节数组,通过ResponseEntity<byte[]>返回
                byte[] b = bos.toByteArray();
                log.info("接收到的文件大小为:" + b.length);
                HttpStatus status = HttpStatus.OK;
                String imageName = "0001.mp4";
                headers.setContentType(MediaType.ALL.APPLICATION_OCTET_STREAM);
                headers.add("Content-Disposition", "attachment;filename=" + imageName);
                entity = new ResponseEntity<>(b, headers, status);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return entity;
        }
    
        /**
         * 文件(二进制数据)下载
         *
         * @param fileType 文件类型
         * @return
         */
        @GetMapping("/downloadFile")
        public ResponseEntity<byte[]> downloadFile(String fileType) {
    
            log.info("参数fileType: " + fileType);
            HttpHeaders headers = new HttpHeaders();
            ResponseEntity<byte[]> entity = null;
            InputStream in = null;
            try {
                in = new FileInputStream(new File("C:\\Users\\user.DESKTOP-8A9L631\\Desktop\\遂人\\图片\\0001.png"));
                int available = in.available();
                log.info("文件大小={}", available);
                byte[] bytes = new byte[available];
                String imageName = "001.png";
                imageName = new String(imageName.getBytes(), "iso-8859-1");
                in.read(bytes);
                headers.setContentType(MediaType.ALL.APPLICATION_OCTET_STREAM);
                headers.add("Content-Disposition", "attachment;filename=" + imageName);
                entity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return entity;
        }
    
    }
    

    三、 消费者调用

    1.OrderController 控制层

    
    @Slf4j
    @RestController
    @AllArgsConstructor
    @RequestMapping("order")
    public class OrderController {
    
        private final OrderService orderService;
    
        /**
         * 上传功能
         * @param file MultipartFile
         * @date: 2021/4/14 10:21
         * @return: UploadResp
         */
        @PostMapping("uploadFile")
        public UploadResp uploadFile(@RequestParam("file") MultipartFile file) {
    
            return orderService.uploadFile(file);
        }
    
    
        /**
         * 下载功能
         * @param response
         * @param fileUrl
         * @date: 2021/4/14 10:21
         * @return: void
         */
        @GetMapping("getObject")
        public void getObject(HttpServletResponse response, String fileUrl) {
    
            orderService.getObject(response, fileUrl);
        }
    }

    2. OrderServiceImpl 消费者服务调用

    
    @Service
    @AllArgsConstructor
    @Slf4j(topic = "OrderServiceImpl")
    public class OrderServiceImpl implements OrderService {
    
        private final FileDownFeign fileDownFeign;
        private final FileUploadFeign fileUploadFeign;
    
    
        @Override
        public void getObject(HttpServletResponse response, String fileUrl) {
    
            ResponseEntity<byte[]> responseEntity = fileDownFeign.downloadFile(fileUrl);
            BufferedInputStream bis = null;
            if (Objects.nonNull(responseEntity)) {
                byte[] body = responseEntity.getBody();
                if (Objects.nonNull(body)) {
                    try {
                        log.info("文件大小==>:{}", body.length);
                        String filename = "20210113001.jpg";
                        response.setContentType("application/octet-stream");
                        response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
                        InputStream is = new ByteArrayInputStream(body);
                        bis = new BufferedInputStream(is);
                        OutputStream os = response.getOutputStream();
                        byte[] buffer = new byte[2048];
                        int i = bis.read(buffer);
                        while (i != -1) {
                            os.write(buffer, 0, i);
                            i = bis.read(buffer);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (bis != null) {
                            try {
                                bis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
    
            }
    
        }
        @Override
        public UploadResp uploadFile(MultipartFile file) {
    
            log.info("uploadFile==>");
            String type = "suirenow";
            UploadResp uploadResp = fileUploadFeign.uploadFile(file, type);
            if (Objects.nonNull(uploadResp)) {
                log.info("fileUploadFeign.uploadFile.resp uploadResp={}", JSON.toJSONString(uploadResp));
            }
            return uploadResp;
        }
    
    }
    

     

     

    展开全文
  • 搭建好简单版本的feign客户端与服务端,本文...-- 引入文件feign文件上传依赖 --> <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactI..
  • feign文件上传(多文件,单个文件)

    千次阅读 2019-09-18 18:52:52
    最近有需求,对文件进行解析后,上传到fastdfs里面,之间涉及到多个服务的调用,需要用到feign进行多文件上传,网上参考了好多,要么只实现了单文件上传,多文件的时候就会报错,现在总结一下该问题 <spring-...
  • Feign 文件上传配置

    2019-01-22 13:42:40
    FeignClient @FeignClient(name = ServiceConstant.RENREN_OSS_SERVER, configuration = OssFeignClient.MultipartSupportConfig.class) public interface OssFeignClient { ... * 文件上传 * @param file...
  • Spring Cloud Feign文件上传(File及MultipartFile)说明MultipartFile文件上传本地File对象上传 说明 当使用Spring Cloud Feign需要上传文件分两种情况:一种是前端上传到微服务,微服务调用Feign接口上传到另一个...
  • 参考一:Spring Cloud Feign文件传输的示例代码参考二:Spring Cloud Feign的文件上传实现过期则参考:Feign 如何支持进行文件上传 | Spring For AllSpring Cloud Feign的文件上传实现...
  • feign文件上传终极解决方案 maven需要增加依赖 &amp;amp;amp;lt;dependency&amp;amp;amp;gt; &amp;amp;amp;lt;groupId&amp;amp;amp;gt;io.github.openfeign.form&amp;amp;amp;lt;/groupId&...
  • 在springcloud feign 这个问题上处理了很久,一直报 Content-Type “multipart/form-data” not set for request body of type CommonsMultipartFile 错误,需要有这个问题的可以一起来解决 一直报multipart/form-...
  • Feign中接口方法的参数是文件类型时要使用**@RequestPart注解,并要设置ContentType为multipart/form-data**。 feign接口: @PostMapping(value = "/student/upload",consumes = MediaType.MULTIPART_FORM_DATA_...
  • 如何还不熟悉如何使用 Spring cloud Feign 实现文件上传。 可以参考翟永超 Spring Cloud Feign文件上传实现 本篇主要介绍如何构造MultipartFile,首先我们通过@RequestPart(&amp;quot;file&amp;quot;)和@...
  • Springboot Feign文件上传

    2019-09-18 06:59:58
    文件上传 File 转 Multi FileInputStream fileInputStream = new FileInputStream(file); MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), ContentType.TEXT_PLAIN.toString(), ...
  •  最近项目中需要用feign调用cloud微服务实现文件上传,但是FeignClient调用接口时不支持上传文件;  本项目采用Feign-form扩展库进行实现文件上传,期间也遇到了很多问题,在这里就和大家分享一下遇到的问题和...
  • 调用公司的一个文件上传接口 </p><p>用的fegin调用</p><p>代码如下</p><p>/**</p><p> *</p><p> * 文件上传</p><p> */</p><p>@RestController</p><p>@RequestMapping(value = "api/v1/file/actions")</p><p>...
  • Springcloud配置Feign文件上传支持

    千次阅读 热门讨论 2018-07-27 13:33:43
    springcloud和其他框架不同的是需要跨模块地调用接口,所以如果在传递文件参数的时候不进行特殊处理的话是没办法成功调用接口的。 首先处理服务A: 需要加入对应的依赖(如果springboot版本高于2.0,feign-...
  • 文件上传参考文档:http://blog.didispace.com/spring-cloud-starter-dalston-2-4/ 文件下载参考文档:https://blog.csdn.net/aaronsimon/article/details/82710979 我的spring boot ,spring cloud 版本是: <...
  • springboot 1.5.1 ...突然发现文件上传失效。。。之前解决掉的问题又再次出现 问题收集如下: 1.Feign library does not support Multipart requests 2. The current request is not a multipart ...
  • springcloud Feign 文件上传/输入流上传

    千次阅读 2020-07-30 10:36:29
    1.1 feign客户端接口(写在你的业务的微服务里) import java.util.Map; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; import org....

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,967
精华内容 1,586
关键字:

feign文件上传