Android to servlet image upload to the server
I created a servlet that accepts images from the android app that comes to self. I receive bytes on my servlet, however, I want to be able to save the image with the original name on the server. How do I do it. I don’t want to use Apache Commons. Are there other solutions that work for me?
Thanks
Solution
Send it as multipart/form-data to the MultipartEntity
built into Android With the help of the class request HttpClient API
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/uploadservlet");
MultipartEntity entity = new MultipartEntity();
entity.addPart("fieldname", new InputStreamBody(fileContent, fileContentType, fileName));
httpPost.setEntity(entity);
HttpResponse servletResponse = httpClient.execute(httpPost);
Then in the servlet’s doPost()
method, extract the portion using Apache Commons FileUpload.
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.getFieldName().equals("fieldname")) {
String fileName = FilenameUtils.getName(item.getName());
String fileContentType = item.getContentType();
InputStream fileContent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
I dont want to use apache commons
Use this unless you are using Servlet 3.0 that supports multipart/form-data
HttpServletRequest #getParts()
out of the box, you need to reinvent a multipart/form data parser yourself according to RFC2388. It will only bite you in the long run. Hard. I don’t really see any reason why you don’t use it. Is it simple ignorance? At least not that hard. Just put commons-fileupload.jar and commons-io.jar
into the /WEB-INF/lib
folder and use the example above. Nothing more. You can find another example here.