springcloud中feign檔案上傳、下載

jasnet_u發表於2018-09-21

檔案上傳、下載也是實際專案中會遇到的場景,本篇我們介紹下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下載檔案即可。

 ~~

 

 

 

相關文章