将图像作为多部分文件接收到休息服务

Receive Image as multipart file to rest service

我正在公开一个 restful 网络服务,我想在 json 正文请求中接受图像作为多部分文件 我在任何地方都找不到样本json 请求以便从休息中点击我的休息服务 client.my 休息服务使用 class 声明上方的此字段 @Consumes({MediaType.APPLICATION_JSON,MediaType.MULTIPART_FORM_DATA} ) 谁能给我一个样品 json 请求

multipart/form-data的目的是在一个请求中发送多个部分。这些部分可以有不同的媒体类型。所以你不应该混合 json 和图像,而是添加两部分:

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 客户端框架,您可以像这样创建此请求:

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();
}