Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image from android to java servlet and save it

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;
}
like image 905
Ohadza Avatar asked May 11 '12 12:05

Ohadza


1 Answers

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.

like image 175
BalusC Avatar answered Nov 09 '22 08:11

BalusC