将图像作为多部分文件接收以进行休息服务 [英] Receive Image as multipart file to rest service
问题描述
我正在公开一个宁静的Web服务,我想在 json正文请求中将图像作为多部分文件接受,但我在任何地方都找不到示例json请求,从而无法从rest客户端访问我的rest服务.my rest服务在类声明@Consumes({MediaType.APPLICATION_JSON,MediaType.MULTIPART_FORM_DATA})上方使用此字段 谁能给我一个示例json请求
I am exposing a restful webservice, where i want to accept image as multipart file in the json body request i dont find anywhere a sample json request so as to hit my rest service from a rest client.my rest service uses this field above the class declaration @Consumes({MediaType.APPLICATION_JSON,MediaType.MULTIPART_FORM_DATA}) can anyone please get me a sample json request
推荐答案
multipart/form-data
的目的是在一个请求中发送多个部分.零件可以具有不同的媒体类型.因此,您不应将json和图片混合使用,而应添加两部分:
The purpose of multipart/form-data
is to send multiple parts in one request. The parts can have different media types. So you should not mix json and the image but add two parts:
POST /some-resource HTTP/1.1
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="json"
Content-Type: application/json
{ "foo": "bar" }
--AaB03x--
Content-Disposition: form-data; name="image"; filename="image.jpg"
Content-Type: application/octet-stream
... content of image.jpg ...
--AaB03x--
使用RESTeasy客户端框架,您可以这样创建此请求:
With the RESTeasy client framework you would create this request like this:
WebTarget target = ClientBuilder.newClient().target("some/url");
MultipartFormDataOutput formData = new MultipartFormDataOutput();
Map<String, Object> json = new HashMap<>();
json.put("foo", "bar");
formData.addFormData("json", json, MediaType.APPLICATION_JSON_TYPE);
FileInputStream fis = new FileInputStream(new File("/path/to/image"));
formData.addFormData("image", fis, MediaType.APPLICATION_OCTET_STREAM_TYPE);
Entity<MultipartFormDataOutput> entity = Entity.entity(formData, MediaType.MULTIPART_FORM_DATA);
Response response = target.request().post(entity);
可以这样概括:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(MultipartFormDataInput input) throws Exception {
Map<String, Object> json = input.getFormDataPart("json", new GenericType<Map<String, Object>>() {});
InputStream image = input.getFormDataPart("image", new GenericType<InputStream>() {});
return Response.ok().build();
}
这篇关于将图像作为多部分文件接收以进行休息服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!