3 java android servlets file-upload
我创建了一个servlet,它接受来自我的android app的图像.我在servlet上接收字节,但是,我希望能够在服务器上保存带有原始名称的图像.我怎么做.我不想使用apache commons.还有其他解决方案对我有用吗?
谢谢
在Android的内置HttpClient API类的帮助下将其作为multipart/form-data请求发送.MultipartEntity
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);
Run Code Online (Sandbox Code Playgroud)
然后在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);
}
Run Code Online (Sandbox Code Playgroud)
我不想使用apache commons
除非您使用支持multipart/form-data请求的Servlet 3.0,否则您HttpServletRequest#getParts()需要根据RFC2388自行重新发明multipart/form-data解析器.它只能长期咬你.硬.我真的没有看到你为什么不使用它的任何理由.这是无知吗?这至少不是那么难.只需删除commons-fileupload.jar并commons-io.jar在/WEB-INF/lib文件夹中并使用上面的示例.而已.你可以在这里找到另一个例子.
| 归档时间: |
|
| 查看次数: |
4960 次 |
| 最近记录: |