Java 如何编写一个接受二进制文件(pdf)的restful web服务

Java 如何编写一个接受二进制文件(pdf)的restful web服务,java,web-services,rest,attachment,Java,Web Services,Rest,Attachment,我正试图用java编写一个restful web服务,它将使用几个字符串参数和一个二进制文件(pdf)参数 我知道如何处理字符串,但我正在处理二进制文件。有什么想法/例子吗 这是我到目前为止所拥有的 @GET @ConsumeMime("multipart/form-data") @ProduceMime("text/plain") @Path("submit/{client_id}/{doc_id}/{html}/{password}") public Response submit(@Pat

我正试图用java编写一个restful web服务,它将使用几个字符串参数和一个二进制文件(pdf)参数

我知道如何处理字符串,但我正在处理二进制文件。有什么想法/例子吗

这是我到目前为止所拥有的

@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();
}
因为我已经发布了这篇文章,所以有答案的链接已经被删除,下面是我的实现

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

您可以将二进制附件存储在请求主体中。或者,请在此处查看此邮件列表存档:

它建议使用Commons FileUpload获取文件并适当地上传

此处使用MIME多部分API的另一种替代方法:

使用jersey restful web服务上载文件的示例程序 需要Jar文件(从Apache站点下载):commons-fileupload.Jar,commons-io.Jar

package com.sms.web;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


@Path("/UploadTest")
public class UploadData {


    @POST 
    // public String upload(@Context HttpServletRequest request, @PathParam("myfile") String fileName) throws Exception {
    public String upload(@Context HttpServletRequest request) throws Exception {

        String response = "none";

        if (ServletFileUpload.isMultipartContent(request)) { 

            response="got file in request";

            // Create a factory for disk-based file items 
            DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory();

            String path = request.getRealPath("") + File.separatorChar + "publishFiles" + File.separatorChar;

            // File f = new File(path + "myfile.txt");
            // File tmpDir = new File("c:\\tmp");

            File destinationDir = new File(path);


            // Set the size threshold, above which content will be stored on disk.
            // fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB

            // Set the temporary directory to store the uploaded files of size above threshold.
            // fileItemFactory.setRepository(tmpDir);

            // Create a new file upload handler             
            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

            try {
                /*
                 * Parse the request
                 */
                List items = uploadHandler.parseRequest(request);
                Iterator itr = items.iterator();

                while(itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    /*
                     * Handle Form Fields.
                     */
                    if(item.isFormField()) {
                        response += "<BR>" + "Field Name = "+item.getFieldName()+", Value = "+item.getString();
                    } else {
                        //Handle Uploaded files.
                        response += "<BR>" + "File Field Name = "+item.getFieldName()+
                            ", File Name = "+item.getName()+
                            ", Content type = "+item.getContentType()+
                            ", File Size = "+item.getSize();
                        /*
                         * Write file to the ultimate location.
                         */
                        File file = new File(destinationDir,item.getName());
                        item.write(file);
                    }
                }
            }catch(FileUploadException ex) {
                response += "Error encountered while parsing the request " + ex;
            } catch(Exception ex) {
                response += "Error encountered while uploading file " + ex;
            }
        } 

        return response;

        }
}
package com.sms.web;
导入java.io.File;
导入java.util.Iterator;
导入java.util.List;
导入javax.ws.rs.POST;
导入javax.ws.rs.Path;
导入javax.ws.rs.core.Context;
导入javax.servlet.http.HttpServletRequest;
导入org.apache.commons.fileupload.FileItem;
导入org.apache.commons.fileupload.FileUploadException;
导入org.apache.commons.fileupload.disk.DiskFileItemFactory;
导入org.apache.commons.fileupload.servlet.ServletFileUpload;
@路径(“/UploadTest”)
公共类上载数据{
@职位
//公共字符串上载(@Context HttpServletRequest请求,@PathParam(“myfile”)字符串文件名)引发异常{
公共字符串上载(@Context-HttpServletRequest-request)引发异常{
字符串响应=“无”;
if(ServletFileUpload.isMultipartContent(请求)){
response=“请求中已获取文件”;
//为基于磁盘的文件项创建工厂
DiskFileItemFactory fileItemFactory=新的DiskFileItemFactory();
字符串路径=request.getRealPath(“”+File.separatorChar+“publishFiles”+File.separatorChar;
//文件f=新文件(路径+“myfile.txt”);
//文件tmpDir=新文件(“c:\\tmp”);
File destinationDir=新文件(路径);
//设置大小阈值,超过该阈值,内容将存储在磁盘上。
//fileItemFactory.setSizeThreshold(1*1024*1024);//1 MB
//设置临时目录以存储大小超过阈值的上载文件。
//setRepository(tmpDir);
//创建新的文件上载处理程序
ServletFileUpload uploadHandler=新的ServletFileUpload(fileItemFactory);
试一试{
/*
*解析请求
*/
列表项=uploadHandler.parseRequest(请求);
迭代器itr=items.Iterator();
while(itr.hasNext()){
FileItem=(FileItem)itr.next();
/*
*处理表单字段。
*/
if(item.isFormField()){
响应+=”
“+”字段名=“+item.getFieldName()+”,值=“+item.getString(); }否则{ //处理上传的文件。 响应+=”
“+”文件字段名=“+item.getFieldName()+ ,File Name=“+item.getName()+ ,Content type=“+item.getContentType()+ ,File Size=“+item.getSize(); /* *将文件写入最终位置。 */ File File=新文件(destinationDir,item.getName()); 项目。写入(文件); } } }catch(FileUploadException-ex){ response+=“解析请求时遇到错误”+ex; }捕获(例外情况除外){ 响应+=“上传文件时遇到错误”+ex; } } 返回响应; } }
将您的解决方案添加为答案
@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;
}