![](/img/trans.png)
[英]How To Pass Multipart Image File as parameter to a POST REST Service
[英]Receive Image as multipart file to rest service
我正在暴露一個寧靜的網絡服務,我想在json主體請求中接受圖像作為多部分文件,但我找不到任何示例json請求,以便從rest客戶端訪問我的rest服務。我的rest服務在類上方使用此字段聲明@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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.