Receive Image as multipart file to rest service

穿精又带淫゛_ 提交于 2021-02-18 18:12:21

问题


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


回答1:


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--

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

Which can be cosumed like this:

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


来源:https://stackoverflow.com/questions/33607492/receive-image-as-multipart-file-to-rest-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!