我尝试使用servlet和JSP实现图片上传。
我的JSP页面非常简单,只有以下形式:
#sql-1964_4
<form method="post" action="${pageContext.request.contextPath}/uploader" enctype="multipart/form-data">
<input type="file" name="file" value="Select an image..." />
<input type="submit" value="Upload Now" />
</form>
中描述了相应的servlet和servlet-mapping
我的web.xml
方法看起来像:
doPost
但编译器在以下行抱怨:protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
FileItemFactory itemFactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(itemFactory);
if (!contentType.equals("image/png")) {
out.println("Only PNG image files supported.");
continue;
}
try {
List<FileItem> items = upload.parseRequest(request); // here is an error
for (FileItem item : items) {
String contentType = item.getContentType();
File uploadDir = new File(UPLOAD_DIR);
File file = File.createTempFile("img", ".png", uploadDir);
item.write(file);
out.println("File uploaded.");
}
} catch (FileUploadException e) {
out.println("Upload failed.");
return;
}
}
:
FileUploadBase文件中的方法
List<FileItem> items = upload.parseRequest(request);
不适用于参数(HttpServletRequest)。
在答案How to upload files to server using JSP/Servlet?中,此方法不会产生任何错误:
parseRequest(RequestContext)
答案 0 :(得分:1)
如果我在这里看到org.apache.commons.fileupload 请求应该是ServletRequestContext而不是HttpServletRequest:
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(new ServletRequestContext(request));
答案 1 :(得分:0)
此代码应解决问题
DiskFileItemFactory diskFactory = new DiskFileItemFactory();
diskFactory.setSizeThreshold(4000);
diskFactory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload uploadHandler = new ServletFileUpload(diskFactory);
List<FileItem> items = upload.parseRequest(request);