从客户端将文件作为参数发送到REST服务?

我的要求是通过一个客户端将文件发送到REST服务。 该服务将处理该文件。 我正在使用Jersey API来实现这一点。 但我在很多文章中搜索过,没有任何关于如何从客户端传递文件以及REST服务将如何检索文件的信息 ……如何实现这一目标?

我没有使用Servlets来创建REST服务。

假设您在客户端和服务器端都使用Jersey,这里有一些代码可以扩展:

服务器端:

@POST @Path("/") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile(final MimeMultipart file) { if (file == null) return Response.status(Status.BAD_REQUEST) .entity("Must supply a valid file").build(); try { for (int i = 0; i < file.getCount(); i++) { System.out.println("Body Part: " + file.getBodyPart(i)); } return Response.ok("Done").build(); } catch (final Exception e) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e) .build(); } } 

上面的代码实现了一个接受POST的多部分(文件)数据的资源方法。 它还说明了如何遍历传入(多部分)请求中的所有单个身体部位。

客户:

 final ClientConfig config = new DefaultClientConfig(); final Client client = Client.create(config); final WebResource resource = client.resource(ENDPOINT_URL); final MimeMultipart request = new MimeMultipart(); request.addBodyPart(new MimeBodyPart(new FileInputStream(new File( fileName)))); final String response = resource .entity(request, "multipart/form-data") .accept("text/plain") .post(String.class); 

上面的代码只是将文件附加到多部分请求,并将请求发送到服务器。 对于客户端和服务器端代码,依赖于Jersey和JavaMail库。 如果您使用的是Maven,可以使用以下依赖项轻松下载这些内容:

  com.sun.jersey jersey-core 1.17    com.sun.jersey jersey-server 1.14    com.sun.jersey jersey-client 1.17   com.sun.jersey jersey-json 1.17   javax.mail mail 1.4.6  

根据需要调整依赖项版本

我是假设,因为它是一个MimeMultipart类型,我不能只发送一个,但多个文件或附加信息可能作为字符串或其他什么,只做一个简单的post,只需添加包含不同文件或其他的多个MimeBodyParts ? 例如:

 final MimeMultipart request = new MimeMultipart(); request.addBodyPart(new MimeBodyPart(new FileInputStream(new File( fileOne))), 0); request.addBodyPart(new MimeBodyPart(new FileInputStream(new File( fileTwo))), 1); 

等等