溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringCloud使用Feign文件上傳、下載

發(fā)布時(shí)間:2020-09-19 15:53:15 來(lái)源:腳本之家 閱讀:318 作者:jasnet_u 欄目:編程語(yǔ)言

文件上傳、下載也是實(shí)際項(xiàng)目中會(huì)遇到的場(chǎng)景,本篇我們介紹下springcloud中如何使用feign進(jìn)行文件上傳與下載。

還是使用feign 進(jìn)行http的調(diào)用。

一、Feign文件上傳

服務(wù)提供方j(luò)ava代碼:

/**
 * 文件上傳
 * @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();//文件的絕對(duì)路徑
 } catch (IllegalStateException | IOException e) {
  e.printStackTrace();
 }
  return "failure";
}

服務(wù)提供方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);

服務(wù)消費(fèi)方:

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文件下載

服務(wù)提供方j(luò)ava代碼:

/**
  * 文件(二進(jìn)制數(shù)據(jù))下載
  * @param fileType 文件類型
  * @return
  */
  @RequestMapping("/downloadFile")
  public ResponseEntity<byte[]> downloadFile(String fileType,HttpServletRequest request ){
   
   System.out.println(request.getParameter("fileType"));
   System.out.println("參數(shù)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下載文件的中文名稱亂碼的問(wèn)題
   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下載文件名空格變+號(hào)問(wèn)題
   } 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;
 }

服務(wù)提供方feign api接口 

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

服務(wù)消費(fèi)方

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

注:實(shí)際項(xiàng)目中如果上傳的文件太大,可以使用ftp服務(wù)器保存上傳的文件,直接在controller端調(diào)用ftp接口即可。

如果下載的文件太大,則調(diào)用service端接口可返回一個(gè)ftp文件資源路徑,然后在controller端調(diào)用ftp下載文件即可。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI