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