尝试将文件上传到JAX-RS(球衣)服务器 [英] Trying to upload a file to a JAX-RS (jersey) server

查看:146
本文介绍了尝试将文件上传到JAX-RS(球衣)服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Jersey的multipart / form-data客户端上传文件和其他表单数据。我正在使用Jersey上传到REST Web服务。这里是服务器代码:

$ $ p $
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces( MediaType.APPLICATION_JSON)
public String create(@FormDataParam(file)InputStream file,
@FormDataParam(file)FormDataContentDisposition fileInfo,
@FormDataParam(name)字符串名称,
@FormDataParam(description)字符串描述){
成分成分=新成分();
ingredient.setName(name);
ingredient.setDescription(description);
ingredient.setImageName(fileInfo.getFileName());
ingredient.setImagePath(context.getRealPath(/ resources / uploads /));
// TODO保存文件。
尝试{
JSONObject json = new JSONObject();
试试{
ingredientService.create(成分);
} catch(final InvalidParameterException ex){
logger.log(Level.INFO,ex.getMessage());
json.put(result,false);
json.put(error,ex.getMessage());
返回json.toString();
} catch(final GoodDrinksException ex){
logger.log(Level.WARNING,null,ex);
json.put(result,false);
json.put(error,ex.getMessage());
返回json.toString();

json.put(成分,JsonUtil.ingredientToJSON(成分));
return json.put(result,true).toString();
} catch(JSONException ex){
logger.log(Level.SEVERE,null,ex);
返回{\result \,false};




$ b我已经使用基本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 / ingredients 
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 hand leUpload(@FormDataParam(file)InputStream流)抛出异常{
return Response.ok(IOUtils.toString(stream))。build();






$二,客户端发布文件的方法
(String url,String fileName){
InputStream stream = getClass()。getClassLoader()。getResourceAsStream()文件名);
FormDataMultiPart part = new FormDataMultiPart()。field(file,stream,MediaType.TEXT_PLAIN_TYPE);

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

三,测试环境:

 服务器服务器; 

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

$ b $ @
之后public void()抛出Exception {
server.stop();
}

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

最后,maven依赖关系:

 <依赖关系> 
<依赖>
< groupId> junit< / groupId>
< artifactId> junit< / artifactId>
< version> 4.8.2< / version>
< scope> test< / scope>
< /依赖>
<依赖>
< groupId> com.sun.jersey< / groupId>
< artifactId>球衣服务器< / artifactId>
< version> 1.6< / version>
< /依赖>
<依赖>
< groupId> com.sun.jersey< / groupId>
< artifactId>球衣客户端< / artifactId>
< version> 1.6< / version>
< /依赖>
<依赖>
< groupId> com.sun.jersey.contribs< / groupId>
< artifactId>球衣多部分< / artifactId>
< version> 1.6< / version>
< /依赖>
<依赖>
< groupId> org.mortbay.jetty< / groupId>
< artifactId> jetty-embedded< / artifactId>
< version> 6.1.26< / version>
< /依赖>
<依赖>
< groupId> commons-io< / groupId>
< artifactId> commons-io< / artifactId>
< version> 2.0.1< / version>
< /依赖>
< /依赖关系>

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


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?

解决方案

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:

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

Second, the client method posting the file:

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

Third, the test environment:

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

Finally, the maven dependencies:

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

The file.txt is at the root of the classpath and contains Hello, World.

这篇关于尝试将文件上传到JAX-RS(球衣)服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆