我试图用Java编写RESTful Web服务,将采取一些字符串PARAMS和二进制文件(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;
}
@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;
}
您可以将二进制附件存储在请求的主体来代替。 另外,在这里看看这个邮件列表存档:
http://markmail.org/message/dvl6qrzdqstrdtfk
它建议使用通用FileUpload取文件,并适当地上传。
这里使用MIME多API另一种选择:
http://n2.nabble.com/File-upload-with-Jersey-td2377844.html
样本程序中使用的球衣RESTful Web服务上传文件
需要Jar文件(Apache的网站下载):公地fileupload.jar,公地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;
}
}