gpt4 book ai didi

java - 尝试将文件上传到 JAX-RS( Jersey )服务器

转载 作者:搜寻专家 更新时间:2023-10-30 20:59:49 25 4
gpt4 key购买 nike

我正在尝试使用带有 Jersey 的 multipart/form-data 客户端上传文件和其他表单数据。我正在使用 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--

为了使它正常工作,我在客户端中做错了什么?

最佳答案

如果您想将字符串添加到 FormDataMultiPart 中,只需使用 .field("name", "value") 方法,方法与用于文件的方法相同附件(queryParam 不起作用)。

下面是一个工作示例:

首先,服务器部分以字符串形式返回读取文件的内容:

@Path("file")
public class FileResource {

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response handleUpload(@FormDataParam("file") InputStream stream) throws Exception {
return Response.ok(IOUtils.toString(stream)).build();
}
}

二、发送文件的客户端方法:

public void upload(String url, String fileName) {
InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName);
FormDataMultiPart part = new FormDataMultiPart().field("file", stream, MediaType.TEXT_PLAIN_TYPE);

WebResource resource = Client.create().resource(url);
String response = resource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
assertEquals("Hello, World", response);
}

三、测试环境:

Server server;

@Before
public void before() throws Exception {
server = new Server(8080);
server.addHandler(new WebAppContext(WEB_INF_DIRECTORY, "/"));
server.start();
}

@After
public void after() throws Exception {
server.stop();
}

@Test
public void upload() {
upload("http://localhost:8080/file", "file.txt");
}

最后,maven依赖:

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-embedded</artifactId>
<version>6.1.26</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
</dependencies>

file.txt 位于类路径的根目录,包含 Hello, World

关于java - 尝试将文件上传到 JAX-RS( Jersey )服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com