当前位置: 首页 > 面试题库 >

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

柴寂离
2023-03-14
问题内容

我正在尝试使用带有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--

我在客户端做错了什么才能使其正常工作?


问题答案:

如果要将Strings添加到FormDataMultiPartjust .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上开发简单的web服务。我是java技术新手,根据几篇文章,我决定将JAX-RS(Jersey)与嵌入式http服务器(Grizzly2)结合使用,因为它看起来适合构建REST服务,部署似乎很简单。 在我的开发环境中,所有工作都很完美(使用IntllijIdea)。 但当我尝试在测试服务器上部署时,每个请求都返回“500内部错误”(偶数/application.wadl) 简单资源

  • 我在WAS 8.0上部署了一个JAX-RS WS应用程序,其中包含一个空的2.4web.xml,这个类扩展了'javax.WS.rs.core.application'和2个资源,它工作得很好。 如何在WAS7.0上部署JAX-RS应用程序而不使用Jersey或任何其他与应用程序服务器相关的类? 谢谢

  • 我有一个服务器Weblogic 12.1.3,带有JAX-RS 2。x作为共享库安装(参见。https://docs.oracle.com/middleware/1213/wls/RESTF/use-jersey20-ri.htm#RESTF297). 该共享库包括例如javax。ws。rs-api-2.0。jar和jersey-media-multipart-2.5.1。jar。 请注意,我不确

  • 问题内容: 我真的很困惑。我已经尝试过使用tomcat的Jax-rs并使用所有能够使用调用我的服务的注释。因此,没有Jax- rs,我可以简单地拥有一个servlet并调用我的服务。同样,正如我尝试过的那样,有jax-rs和jersey(我研究了的实现)以及web.xml中的以下内容。 然后,我在GET上具有与JAX-RS相同的注释,可以使用正确的URL调用我的服务。 我的问题是,为什么球衣使用s

  • 我想在Grizzly 2上运行JAX-RS 2.0/jer,但我现在不知道如何设置它。我发现了以下Maven依赖项: 我需要什么Java代码才能在灰熊上运行泽西岛?

  • 与上一篇教程中讲解的文件下载一样,JAX-RS也可以实现上传文件,上传的文件类型可以是:图像文件,PDF文件,Excel文件,文本文件等。 注释用于提及服务类中的参数。 用于提供文件上载的信息。 要使用JAX-RS API上传文件,我们将使用jersey 来实现。首先打开Eclipse,创建一个动态Web项目:JAXRSFileUpload,结构如下所示 - 要通过jersey实现上传文件,需要在