FeignCilent转发文件上传时遇到的一系列问题
这个问题在网上查到了一些资料,这里做下总结。
参考:
https://www.jianshu.com/p/3ecbc0062411
https://blog.csdn.net/qq_35307947/article/details/105097870
问题
1、服务端获取不到文件
2、获取文件失败
the request was rejected because no multipart boundary was found
原因
feignClient转发MultipartFile时content-type没有boundary,下面的源码报错。
protected byte[] getBoundary(String contentType) {
ParameterParser parser = new ParameterParser();
parser.setLowerCaseNames(true);
// Parameter parser can handle null input
Map<String, String> params = parser.parse(contentType, new char[] {';', ','});
String boundaryStr = params.get("boundary");
if (boundaryStr == null) {
return null;
}
byte[] boundary;
try {
boundary = boundaryStr.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
boundary = boundaryStr.getBytes(); // Intentionally falls back to default charset
}
return boundary;
}
处理
调用方配置自定义FeignConfig。定义multipart/form-data。改用@RequestPart
主要改动代码
调用方
@FeignClient(value = "xxx", configuration = FeignConfig.class)
public interface UserClientService {
@PostMapping(path = "/manager/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResultVO managerImport(@RequestPart("file") MultipartFile multfile);
}
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
public class FeignConfig{
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
pom依赖
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
服务方
@PostMapping("/manager/import")
public ResultVO managerImport(@RequestPart("file") MultipartFile multfile) {
// TODO
}
后记
另外还查到一种方式是用 @RequestLine,但是没成功。