SpringCloud Upload and Download Using Feign File

  • 2021-07-24 10:53:06
  • OfStack

File uploading and downloading are also scenarios encountered in actual projects. In this article, we introduce how to use feign to upload and download files in springcloud.

Or use feign to call http.

1. Feign file upload

Service provider java code:


/**
 *  File upload 
 * @param file  Documents  
 * @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("."));// Suffix 
  
 String uuid =UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
  
 File dest = new File("f:/b13/"+uuid+suffix);
  try {
  file.transferTo(dest);
   
  return dest.getCanonicalPath();// Absolute path of file 
 } catch (IllegalStateException | IOException e) {
  e.printStackTrace();
 }
  return "failure";
}

Service provider Feign api interface:


@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);

Service consumer:

pom.xml


<!--  Import file feign File upload dependency  -->
 <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 code:


@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;
  }
 
}

2. Feign file download

Service provider java code:


/**
  *  Documents ( 2 Binary data) Download 
  * @param fileType  File type 
  * @return
  */
  @RequestMapping("/downloadFile")
  public ResponseEntity<byte[]> downloadFile(String fileType,HttpServletRequest request ){
   
   System.out.println(request.getParameter("fileType"));
   System.out.println(" Parameter 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";
   
   // Deal with IE The Chinese name of the downloaded file is garbled 
   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 Download file name space change + Number problem 
   } 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;
 }

Service Provider feign api Interface


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

Service consumer


@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 ;
}

Note: If the uploaded file in the actual project is too large, you can use the ftp server to save the uploaded file, and call the ftp interface directly at the controller end.

If the downloaded file is too large, call the service interface to return one ftp file resource path, and then call ftp at controller to download the file.


Related articles: