我创建了一个 servlet,它接受来自我的 android 应用程序的图像。我在我的 servlet 上接收字节,但是,我希望能够在服务器上使用原始名称保存此图像。我怎么做。我不想使用 apache 公共(public)资源。有没有其他适合我的解决方案?
谢谢
最佳答案
在 Android 内置 multipart/form-data 的 MultipartEntity
类的帮助下,将其作为 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);
然后在servlet的
doPost()
方法中,使用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);
}
除非您使用的 Servlet 3.0 支持
multipart/form-data
开箱即用的 HttpServletRequest#getParts()
请求,否则您需要基于 RFC2388 自己重新发明一个 multipart/form-data 解析器。从长远来看,它只会咬你。难的。我真的看不出你有什么理由不使用它。是单纯的无知吗?至少没有那么难。只需将 commons-fileupload.jar
和 commons-io.jar
放在 /WEB-INF/lib
文件夹中并使用上面的示例。就是这样。你可以找到 here 另一个例子。关于java - Android 到 servlet 图片上传保存在服务器上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5205273/