0

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);
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
SaNmm
  • 201
  • 1
  • 7
  • 14
  • Related: http://stackoverflow.com/questions/2422468/how-to-upload-files-in-jsp-servlet/2424824#2424824 – BalusC Oct 26 '11 at 23:24

3 Answers3

3

Use something like commons fileupload.

There are examples in the Apache docs, and all over the web.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • can you post an example for this – SaNmm Oct 26 '11 at 21:08
  • 3
    @user964428 Click on the link and look at the user guide, or one of the examples. If you just regurgitate what someone else posts, how will you diagnose/troubleshoot any problems? – Dave Newton Oct 26 '11 at 21:10
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

  1. HttpServletRequest.getParts()
  2. HttpServletRequest.getPart("name");
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
0

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...
}
danb
  • 10,239
  • 14
  • 60
  • 76
  • but I am sending the image to the server so after getting it how can i use it to do some editing on it – SaNmm Oct 29 '11 at 07:19
  • I think that's another question :) but there's alot you can do: http://www.javalobby.org/articles/ultimate-image/ – danb Oct 30 '11 at 23:35