今天在实现后台上传功能时,在feign传输文件时一直出问题,故此记录下实现过程,需特别注意标红代码地方。
此功能实现后台代码分为服务端、客户端:
前台页面调用客户端接口,客户端再调用服务端接口
1.服务端FileController接口:
@RequestMapping(value = "/uploadImageSingle", method = RequestMethod.POST)
public BaseDataResp uploadImage(@RequestParam(value = "file") MultipartFile file) {
BaseDataResp resp = new BaseDataResp();
try {
if(file.isEmpty()){
return BaseDataResp.fail(IGowResultCode.Commons.ERROR_PARAMETER);
}
ArrayList<StorePath> list = new ArrayList();
Set<MetaData> metaDataSet = new HashSet();
StorePath storePath = this.client.uploadImage(new FastImageFile(file.getInputStream(), file.getSize(), FileUtil.getSuffix(file.getOriginalFilename()), metaDataSet));
resp.setData(storePath);
} catch (Exception e) {
ExceptionLogUtil.debugOrError(log, e, e.getMessage() + e.getMessage());
}
resp.setCode(IGowResultCode.Commons.SUCCESS);
return resp;
}
2.客户端接口主要实现代码:
private TSystemFiles uploadFile(CommonsMultipartFile file) throws Exception {
// 需对传进来的File进行转换,直接传参会报400异常
DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
MediaType.ALL_VALUE, true, file.getOriginalFilename());
InputStream input = file.getInputStream();
OutputStream os = fileItem.getOutputStream();
IOUtils.copy(input, os);
MultipartFile multi = new CommonsMultipartFile(fileItem);
// 上传文件
BaseDataResp resp = fileClient.uploadFile(multi);
if(!IGowResultCode.Commons.SUCCESS.equals(resp.getCode())){
throw new UserException(IGowResultCode.Commons.ERROR_UNKNOWN);
}
}
FileClient:
@PostMapping(value = "/file/server/uploadImageSingle", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE} , produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
BaseDataResp uploadFile(@RequestPart(value = "file",required = false) MultipartFile file);
WebConfig:
@Bean
public Encoder multipartFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(new ObjectFactory<HttpMessageConverters>() {
@Override
public HttpMessageConverters getObject() throws BeansException {
return new HttpMessageConverters(new RestTemplate().getMessageConverters());
}
}));
}
maven jar 引用:
<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>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>