我正在嘗試使用servlet和JSP上傳圖像上傳。ServletFileUpload使用servlet和JSP上傳文件時出現parseRequest()編譯錯誤
我的JSP頁是相當簡單的,並且具有唯一的以下形式:
<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映射在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;
}
}
但是,編譯以下行抱怨:List<FileItem> items = upload.parseRequest(request);
:
在文件FileUploadBase方法
parseRequest(RequestContext)
是不適用的參數(HttpServletRequest的)。
雖然在回答How to upload files to server using JSP/Servlet?這種方法不會產生任何錯誤:如果我在這裏看到org.apache.commons.fileupload 請求應ServletRequestContext不HttpServletRequest的
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
絕對正確!非常感謝。 – DimaSan
不客氣。 –