本文介绍了如何编写一个接受二进制文件的 Restful Web 服务 (pdf)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用 Java 编写一个安静的 Web 服务,它需要一些字符串参数和一个二进制文件 (pdf) 参数.
I'm trying to write a restful web service in java that will take a few string params and a binary file (pdf) param.
我了解如何处理字符串,但我对二进制文件很着迷.有什么想法/例子吗?
I understand how to do the strings but I'm getting hung up on the binary file. Any ideas / examples?
这是我目前所拥有的
@GET
@ConsumeMime("multipart/form-data")
@ProduceMime("text/plain")
@Path("submit/{client_id}/{doc_id}/{html}/{password}")
public Response submit(@PathParam("client_id") String clientID,
@PathParam("doc_id") String docID,
@PathParam("html") String html,
@PathParam("password") String password,
@PathParam("pdf") File pdf) {
return Response.ok("true").build();
}
自从我发布了这个,包含答案的链接已被删除,所以这是我的实现.
Since I've posted this the link that had the answer has been removed, so here is my implementation.
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@Path("submit")
public Response submit(@FormDataParam("clientID") String clientID,
@FormDataParam("html") String html,
@FormDataParam("pdf") InputStream pdfStream) {
try {
byte[] pdfByteArray = DocUtils.convertInputStreamToByteArrary(pdfStream);
} catch (Exception ex) {
return Response.status(600).entity(ex.getMessage()).build();
}
}
...
public static byte[] convertInputStreamToByteArrary(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
final int BUF_SIZE = 1024;
byte[] buffer = new byte[BUF_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) > -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
byte[] byteArray = out.toByteArray();
return byteArray;
}
推荐答案
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@Path("submit")
public Response submit(@FormDataParam("clientID") String clientID,
@FormDataParam("html") String html,
@FormDataParam("pdf") InputStream pdfStream) {
try {
byte[] pdfByteArray = DocUtils.convertInputStreamToByteArrary(pdfStream);
} catch (Exception ex) {
return Response.status(600).entity(ex.getMessage()).build();
}
}
...
public static byte[] convertInputStreamToByteArrary(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
final int BUF_SIZE = 1024;
byte[] buffer = new byte[BUF_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) > -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
byte[] byteArray = out.toByteArray();
return byteArray;
}
这篇关于如何编写一个接受二进制文件的 Restful Web 服务 (pdf)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!