SaNmm
SaNmm

Reputation: 201

Sending a image to servlet in java how to get the image in servlet

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);

Upvotes: 0

Views: 3588

Answers (3)

Ramesh PVK
Ramesh PVK

Reputation: 15456

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");

Upvotes: 2

danb
danb

Reputation: 10379

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...
}

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160311

Use something like commons fileupload.

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

Upvotes: 3

Related Questions