[英]Send File as a parameter to a REST Service, from a client?
我的要求是通過一個客戶端將文件發送到REST服務。 該服務將處理文件。 我正在使用Jersey API來實現此目的。 但是我搜索了很多文章,沒有關於如何從客戶端傳遞文件以及REST服務將如何檢索文件的任何信息...如何實現此目的?
而且我沒有使用Servlet創建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,則可以輕松將其下拉,並具有以下依賴性:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.17</version>
</dependency>
<dependency> <!-- only on server side -->
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.14</version>
</dependency>
<dependency> <!-- only on client side -->
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.17</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.6</version>
</dependency>
根據需要調整依賴項版本
我是否假設,因為它是MimeMultipart類型,所以我只能發送一個,而是通過添加多個包含不同文件或其他內容的MimeBodyParts,而只發送一個簡單的帖子,而是發送多個文件或其他信息(例如String或其他形式)? ? 例如:
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);
等等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.