带有文件输入流和 json 正文的 web 服务? [英] webservice with a file inputstream and a json body?
问题描述
我想用 cxf 实现一个网络服务来上传一个文件,其中包含一些关于它的信息.
I would like to implement a webservice with cxf to upload a file with some informations about it contained in the body.
我已经完成但还没有工作的:
What I've done but didn't work yet :
@POST
@Path("/")
@Consumes(MediaType.MULTIPART_FORM_DATA)
User addDocument(
@Multipart(value="metadata", type="application/json") DocMeta metadata,
@Multipart(value="inputstream", type="multipart/form-data") InputStream inputStream)
throws ObjectAlreadyExistsException;
当我尝试使用 curl 请求我的服务时,它不起作用:
When I try to request my service with curl it doesn't work :
curl http://localhost:9090/...
--X POST
-H"Content-Type:multipart/form-data"
-F inputstream=@myFile.txt
-d'{"info1":"info1","info2":"info2"}'
是否真的可以同时拥有多部分数据和带有 cxf 的 json 主体??
Is it really possible to have both multipart data and a json body with cxf ??
提前致谢
马努
推荐答案
是的,这是可能的.但问题在于您的 cURL 请求.您应该将所有部分添加为 --form/-F
.您正在尝试将 JSON 作为普通正文发送.试图让 cURL 出错,它甚至不会发出请求.您还需要为每个部分设置 Content-Type.例如
Yes it's possible. But the problem is with your cURL request. You should add all parts as --form/-F
. You are trying to send the JSON as a normal body. Attempting that I would get an error with cURL, it wouldn't even send out the request. Also you need to set the Content-Type for each part. For example
C:>curl -v -H "Content-Type:multipart/form-data"
-H "Accept:application/json"
-F "stream=@android.png;type=application/octet-stream"
-F "person={"name":"peeskillet"};type=application/json"
-X POST http://localhost:8080/rest/multipart`
(当然都在一行上).这是我用来测试的资源方法.
(All on one line of course). Here's the resource method I used to test.
public static class Person {
public String name;
}
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response postMultiPart(
@Multipart(value="stream", type="application/octet-stream") InputStream img,
@Multipart(value="person", type="application/json") Person person) throws Exception {
Image image = ImageIO.read(img);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new JLabel(new ImageIcon(image)));
frame.setVisible(true);
return Response.ok(person).build();
}
这是我作为文件发送的图像.
It was an image that I sent as a file.
或者,您可以获得一个附件
,这将为您提供有关文件的更多信息.
Alternatively, you can get an Attachment
, which will give you more info on the file.
public Response postMultiPart(
@Multipart(value="stream") Attachment img,
@Multipart(value="person", type="application/json") Person person) throws Exception {
Image image = ImageIO.read(img.getObject(InputStream.class));
- 有关 CXF 支持的更多信息,请参阅多部分支持
这篇关于带有文件输入流和 json 正文的 web 服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!