java 使用 Feign 上传文件 - multipart/form-data
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31752779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File Upload Using Feign - multipart/form-data
提问by btidwell
I'm trying to accomplish a multipart file upload using feign, but I can't seem to find a good example of it anywhere. I essentially want the HTTP request to turn out similar to this:
我正在尝试使用 feign 完成多部分文件上传,但我似乎无法在任何地方找到一个很好的例子。我基本上希望 HTTP 请求类似于这样:
...
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="name"
Larry
--AaB03x
Content-Disposition: form-data; name="file"; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--AaB03x--
Or even...
甚至...
------fGsKo01aQ1qXn2C
Content-Disposition: form-data; name="file"; filename="file.doc"
Content-Type: application/octet-stream
... binary data ...
------fGsKo01aQ1qXn2C--
Do I need to manually build the request body, including generating the multipart boundaries? That seems a bit excessive considering everything else this client can do.
我是否需要手动构建请求正文,包括生成多部分边界?考虑到这个客户可以做的所有其他事情,这似乎有点过分。
采纳答案by NangSaigon
No, you don't. You just need to define a kind of proxy interface method, specify the content-type as: multipart/form-data and other info such as parameters required by the remote API. Here is an example:
不,你没有。您只需要定义一种代理接口方法,指定content-type为:multipart/form-data以及远程API需要的参数等其他信息。下面是一个例子:
public interface FileUploadResource {
@RequestLine("POST /upload")
@Headers("Content-Type: multipart/form-data")
Response uploadFile(@Param("name") String name, @Param("file") File file);
}
The completed example can be found here: File Uploading with Open Feign
完整的示例可以在这里找到:File Uploading with Open Feign
回答by pcan
If you are already using Spring Web, you can try my implementation of a Feign Encoder that is able to create Multipart requests. It can send a single file, an array of files alongwith one or more additional JSON payloads. Here is my test project. If you don't use Spring, you can refactor the code by changing the encodeRequest method in FeignSpringFormEncoder.
如果您已经在使用 Spring Web,您可以尝试我实现的能够创建 Multipart 请求的 Feign Encoder。它可以发送单个文件、一组文件以及一个或多个额外的 JSON 有效负载。这是我的测试项目。如果不使用Spring,可以通过改变FeignSpringFormEncoder中的encodeRequest方法来重构代码。
回答by MBozic
For spring boot 2 and spring-cloud-starter-openfeignuse this code:
对于 spring boot 2 和spring-cloud-starter-openfeign使用以下代码:
@PostMapping(value="/upload", consumes = "multipart/form-data" )
QtiPackageBasicInfo upload(@RequestPart("package") MultipartFile package);
You need to change @RequestParam to @RequestPart in the feign client call to make it work, and also add consumes to the @PostMapping.
您需要在 feign 客户端调用中将 @RequestParam 更改为 @RequestPart 以使其工作,并将消费添加到@PostMapping。