问题
I am sending a image from android phone to server which is a servlet I am using the HttpClient and HttpPost for this and ByteArrayBody for storing the image before sending.
how do i extract the image from the post request in Servlet.
Here is my code for sending the post request
String postURL = //server url;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(postURL);
ByteArrayBody bab = new ByteArrayBody(imageBytes,"file_name_ignored");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("source", bab);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
回答1:
Use something like commons fileupload.
There are examples in the Apache docs, and all over the web.
回答2:
Servlet 3.0 has support for reading multipart data. MutlipartConfig support in Servlet 3.0 If a servelt is annotated using @MutlipartConfig annotation, the container is responsible for making the Multipart parts available through
- HttpServletRequest.getParts()
- HttpServletRequest.getPart("name");
回答3:
use http://commons.apache.org/fileupload/using.html
private DiskFileItemFactory fif = new DiskFileItemFactory();
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
if(!isMultipart)
throw new ServletException("upload using multipart");
ServletFileUpload upload = new ServletFileUpload(fif);
upload.setSizeMax(1024 * 1024 * 10 /* 10 mb */);
List<FileItem> items;
try {
items = upload.parseRequest(req);
} catch (FileUploadException e) {
throw new ServletException(e);
}
if(items == null || items.size() == 0)
throw new ServletException("No items uploaded");
FileItem item = items.get(0);
// do something with file item...
}
来源:https://stackoverflow.com/questions/7908886/sending-a-image-to-servlet-in-java-how-to-get-the-image-in-servlet