简体   繁体   中英

Android to servlet image upload to be saved on server

I have created a servlet that accepts an image from my android app.I am receiving bytes on my servlet, however, I want to be able to save this image with the original name on the server. How do I do that. I dont want to use apache commons. Is there any other solution that would work for me?

thanks

Send it as a multipart/form-data request with help of MultipartEntity class of Android's builtin 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);

And then in servlet's doPost() method, use Apache Commons FileUpload to extract the part.

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

Unless you're using Servlet 3.0 which supports multipart/form-data request out the box with HttpServletRequest#getParts() , you would need to reinvent a multipart/form-data parser yourself based on RFC2388 . It's only going to bite you on long term. Hard. I really don't see any reasons why you wouldn't use it. Is it plain ignorance? It's at least not that hard. Just drop commons-fileupload.jar and commons-io.jar in /WEB-INF/lib folder and use the above example. That's it. You can find here another example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM