我在網上查了很多關於 Spring Cloud 文件上傳的相關資料也花費了不少時間,根據他們提供的方案修改也沒有得到解決,終於在朋友的幫忙下,終於解決了我的問題,也與大家分享了下,如下:
一、項目結構
首先介紹一下項目結構,我們開發的項目結構比較簡單
xxx-api工程:這個工程主要是對外提供接口.
xxx-core工程:這個工程承載核心業務處理.
二、上代碼
對於開發者來說,看代碼比較實在,如下:
xxx-api工程下的文件上傳相關代碼:
1、Controller類(注意紅色的標記)
@ApiOperation("文件上傳接口")
@PostMapping(value = "/fileUpload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public RespMsg<Map<String, String>> fileUpload(@RequestPart(value = "file",required = false) MultipartFile file){
try {
Map<String, String> map = uploadFeginClient.fileUpload(file,"certificate");
return RespMsg.success(map);
} catch (Exception e) {
e.printStackTrace();
return RespMsg.error();
}
}
2、FeginClient類(注意紅色的標記)
/**
* @author 潘浩
* @Title: UserAccountClient.java
* @Description: 文件上傳
*/
@FeignClient(name = "upload", url = "${mallcore.http.url}",
configuration = UploadFeginClient.ClientConfiguration.class)
public interface UploadFeginClient {
/**
* 文件上傳
* @param file
* @return
* @throws Exception
*/
@PostMapping(value = "/mallapi/upload/fileUpload",
produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Map<String, String> fileUpload(@RequestPart(value = "file") MultipartFile file,
@RequestParam(value = "type") String type) throws Exception;
//文件配置轉換 (內部類)
class ClientConfiguration{
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
/**
* @Description // 此處注入的是: ObjectFactory<HttpMessageConverters>
* @Date 23:04 2020/4/9
* @Param []
* @return feign.form.spring.SpringFormEncoder
**/
@Bean
public Encoder feignEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
}
二、xxx-core工程下的相關代碼,如下:
以下是 FeignClient類調用Core工程Controller類,如下:
1、Controller類
@ApiOperation("文件上傳接口.")
@PostMapping(value = "/fileUpload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Map<String, String> fileUpload(@RequestPart(value = "file") MultipartFile file,
@RequestParam(value = "type") String type) throws Exception {
// 這裏將文件上傳到服務器,這個比較好解決的.
return uploadService.fileUpload(file, type);
}