Android to servlet image upload to be saved on ser

2019-03-21 16:56发布

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

1条回答
Summer. ? 凉城
2楼-- · 2019-03-21 17:50

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.

查看更多
登录 后发表回答