6

I've been looking all over for this and nothing worked for me.

I'm trying to upload an image from android app to java servlet and save it in the server. Every solution I found didn't work for me.

What my code currently does: the android app is sending the image to the servlet, when i'm trying to save it the file is created, but it's empty :(

Thanks for your help!

My code in the android client (i_file is the file location on the device):

public static void uploadPictureToServer(String i_file) throws ClientProtocolException, IOException {
    // TODO Auto-generated method stub   
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://192.168.1.106:8084/Android_Server/GetPictureFromClient");
    File file = new File(i_file);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);

    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();

}

My code in the server side:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

        InputStream in = request.getInputStream();
        OutputStream out = new FileOutputStream("C:\\myfile.jpg");
        IOUtils.copy(in, out); //The function is below
        out.flush();
        out.close();

}

IOUtils.copy code:

public static long copy(InputStream input, OutputStream output) throws IOException {
    byte[] buffer = new byte[4096];

    long count = 0L;
    int n = 0;

    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
        count += n;
    }
    return count;
}
Ohadza
  • 159
  • 1
  • 3
  • 8
  • This does not only relate to the client, you must implement it on the server (servlet) as well. Btw: What does `processRequest` do? – home May 11 '12 at 12:48
  • Thank you for the response. I read the info in the link, but I can't seem to figure out the solution for my problem. – Ohadza May 11 '12 at 12:49
  • How does your servlet's code look like? What happens in `processRequest`? – home May 11 '12 at 12:49
  • The processRequest() did nothing so I removed it. Got the answer down here. Thanks for your help @home. – Ohadza May 11 '12 at 13:45

1 Answers1

9

You misinterpreted the problem. The image file is not empty, but the image file is corrupted because you're storing the entire HTTP multipart request body as an image file instead of extracting the part containing the image from the HTTP multipart request body.

You need HttpServletRequest#getPart() to obtain the parts of a multipart request body. If you're already on Servlet 3.0 (Tomcat 7, Glassfish 3, etc), first annotate your servlet with @MultipartConfig

@WebServlet("/GetPictureFromClient")
@MultipartConfig
public class GetPictureFromClient extends HttpServlet {
    // ...
}

then fix your doPost() as follows to grab the part by its name and then its body as input stream:

InputStream in = request.getPart("userfile").getInputStream();
// ...

If you're still not on Servlet 3.0 yet, then grab Apache Commons FileUpload. See also this answer for a detailed example: How to upload files to server using JSP/Servlet?

Oh, please get rid of the Netbeans-generated processRequest() method. It's absolutely not the right way to delegate both doGet() and doPost() to a single processRequest() method and it'll only confuse other developers and maintainers who don't use Netbeans.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks you so much! it's finally working... now I can go to the gym with a smile on my face! P.S I got rid of processRequest(). – Ohadza May 11 '12 at 13:43