我创建了一个 servlet,它接受来自 android 应用程序的图像。我在 servlet 上接收字节,但是,我希望能够使用服务器上的原始名称保存该图像。我怎么做。我不想使用 apache commons。还有其他适合我的解决方案吗?
thanks
将其作为多部分/表单数据 http://www.faqs.org/rfcs/rfc2388.html请求在...的帮助下MultipartEntity
Android 内置类Http客户端API http://developer.android.com/reference/org/apache/http/client/HttpClient.html.
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 文件上传 http://commons.apache.org/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);
}
我不想使用 apache commons
除非你使用的是 Servlet 3.0,它支持multipart/form-data
请求开箱即用HttpServletRequest#getParts() http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getParts(),您需要自己重新发明一个多部分/表单数据解析器RFC2388 http://www.faqs.org/rfcs/rfc2388.html。从长远来看,它只会咬你一口。难的。我真的看不出你有什么理由不使用它。这纯粹是无知吗?至少没那么难。只需放下commons-fileupload.jar
and commons-io.jar
in /WEB-INF/lib
文件夹并使用上面的示例。就是这样。你可以找到here https://stackoverflow.com/questions/2422468/how-to-upload-files-in-jsp-servlet/2424824#2424824另一个例子。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)