尝试将文件上传到 JAX-RS (jersey) 服务器
我正在尝试使用带有 Jersey 的多部分/表单数据客户端上传文件和其他表单数据。我也使用 Jersey 上传到 REST Web 服务。这是服务器代码:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String create(@FormDataParam("file") InputStream file,
@FormDataParam("file") FormDataContentDisposition fileInfo,
@FormDataParam("name") String name,
@FormDataParam("description") String description) {
Ingredient ingredient = new Ingredient();
ingredient.setName(name);
ingredient.setDescription(description);
ingredient.setImageName(fileInfo.getFileName());
ingredient.setImagePath(context.getRealPath("/resources/uploads/"));
// TODO save the file.
try {
JSONObject json = new JSONObject();
try {
ingredientService.create(ingredient);
} catch (final InvalidParameterException ex) {
logger.log(Level.INFO, ex.getMessage());
json.put("result", false);
json.put("error", ex.getMessage());
return json.toString();
} catch (final GoodDrinksException ex) {
logger.log(Level.WARNING, null, ex);
json.put("result", false);
json.put("error", ex.getMessage());
return json.toString();
}
json.put("ingredient", JsonUtil.ingredientToJSON(ingredient));
return json.put("result", true).toString();
} catch (JSONException ex) {
logger.log(Level.SEVERE, null, ex);
return "{\"result\",false}";
}
}
我已经在桌面上使用基本 html 表单测试了服务器代码,它工作正常。问题似乎出在客户端。这是相关的客户端代码。
ClientConfig config = new DefaultClientConfig();
client = Client.create(config);
client.addFilter(new LoggingFilter());
webResource = client.resource("http://localhost:8080/webapp/resources").path("ingredient");
FormDataMultiPart fdmp = new FormDataMultiPart();
if (file != null) {
fdmp.bodyPart(new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
}
fdmp.bodyPart(new FormDataBodyPart("name", ingredient.getName()));
fdmp.bodyPart(new FormDataBodyPart("description", ingredient.getDescription()));
ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class, fdmp);
String string = response.getEntity(String.class);
logger.log(Level.INFO, "response: {0}", string);
我从服务器收到 400 响应“客户端发送的请求在语法上不正确”
这是从记录器中吐出的消息,这个消息没有文件来保持输出简短:
1 > POST http://localhost:8080/webapp/resources/ingredient
1 > Content-Type: multipart/form-data
1 >
--Boundary_5_1545082086_1303666703655
Content-Type: text/plain
Content-Disposition: form-data;name="name"
Adam
--Boundary_5_1545082086_1303666703655
Content-Type: text/plain
Content-Disposition: form-data;name="description"
Test
--Boundary_5_1545082086_1303666703655--
我做错了什么在客户端中使其正常工作?
I'm trying to upload a file and other form data using multipart/form-data client with Jersey. I'm uploading to a REST web service also using Jersey. Here is the server code:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String create(@FormDataParam("file") InputStream file,
@FormDataParam("file") FormDataContentDisposition fileInfo,
@FormDataParam("name") String name,
@FormDataParam("description") String description) {
Ingredient ingredient = new Ingredient();
ingredient.setName(name);
ingredient.setDescription(description);
ingredient.setImageName(fileInfo.getFileName());
ingredient.setImagePath(context.getRealPath("/resources/uploads/"));
// TODO save the file.
try {
JSONObject json = new JSONObject();
try {
ingredientService.create(ingredient);
} catch (final InvalidParameterException ex) {
logger.log(Level.INFO, ex.getMessage());
json.put("result", false);
json.put("error", ex.getMessage());
return json.toString();
} catch (final GoodDrinksException ex) {
logger.log(Level.WARNING, null, ex);
json.put("result", false);
json.put("error", ex.getMessage());
return json.toString();
}
json.put("ingredient", JsonUtil.ingredientToJSON(ingredient));
return json.put("result", true).toString();
} catch (JSONException ex) {
logger.log(Level.SEVERE, null, ex);
return "{\"result\",false}";
}
}
I've tested the server code using a basic html form on my desktop and it works fine. The problem seems to be in the client. Here is the relevant client code.
ClientConfig config = new DefaultClientConfig();
client = Client.create(config);
client.addFilter(new LoggingFilter());
webResource = client.resource("http://localhost:8080/webapp/resources").path("ingredient");
FormDataMultiPart fdmp = new FormDataMultiPart();
if (file != null) {
fdmp.bodyPart(new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
}
fdmp.bodyPart(new FormDataBodyPart("name", ingredient.getName()));
fdmp.bodyPart(new FormDataBodyPart("description", ingredient.getDescription()));
ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class, fdmp);
String string = response.getEntity(String.class);
logger.log(Level.INFO, "response: {0}", string);
I'm getting a 400 response from the server "The request sent by the client was syntactically incorrect"
Here is the message that is spit out of the logger, this one is without a file to keep the output brief:
1 > POST http://localhost:8080/webapp/resources/ingredient
1 > Content-Type: multipart/form-data
1 >
--Boundary_5_1545082086_1303666703655
Content-Type: text/plain
Content-Disposition: form-data;name="name"
Adam
--Boundary_5_1545082086_1303666703655
Content-Type: text/plain
Content-Disposition: form-data;name="description"
Test
--Boundary_5_1545082086_1303666703655--
What am I doing wrong in the client to get this working correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果要将字符串添加到
FormDataMultiPart
,只需使用.field("name", "value")
方法,就像用于文件附件 (queryParam不起作用)。下面是一个工作示例:
首先,服务器部分以字符串形式返回读取文件的内容:
其次,发布文件的客户端方法:
第三,测试环境:
最后,maven 依赖项:
文件。 txt
位于类路径的根目录,包含Hello, World
。If you want to add Strings to the
FormDataMultiPart
just use the.field("name", "value")
method the same way it is used for the file attachment (queryParam does not work).Below is a working sample:
First, the server part which returns the content of the read file as a String:
Second, the client method posting the file:
Third, the test environment:
Finally, the maven dependencies:
The
file.txt
is at the root of the classpath and containsHello, World
.伊夫解决方案在客户端对我不起作用。
我环顾四周,发现:
其中任何一个都不适用于我当前的球衣 1.18(请参阅下面的 pom 摘录)。
大多数问题都在客户端。我会收到如下错误消息:
服务器端使用此代码快速工作(它没有做任何有趣的事情)
上传的InputStream - 满足您的需求)
客户端将使用以下代码:
pom.xml 提取:
Yves solution didn't work for me on the client side.
I looked around a bit and found:
non of which would work with my current jersey 1.18 (see pom extract below).
Most trouble was on the client side. I would get error messages like:
The server side worked quickly with this code (which doesn't do anything interesting with
the uploaded InputStream yet - fit to your needs )
the client side would work with this code:
pom.xml extract:
或者只是编写一个新文件并上传:
Or just write a new file and upload it: