gpt4 book ai didi

java - 使用servlet和JSP上传文件时ServletFileUpload parseRequest()编译错误

转载 作者:行者123 更新时间:2023-11-30 02:42:06 26 4
gpt4 key购买 nike

我正在尝试使用servlet和JSP实现图像上传

我的 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-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;
}
}

但是编译器在以下行中提示:List<FileItem> items = upload.parseRequest(request); :

The method parseRequest(RequestContext) in the file FileUploadBase is not applicable for the arguments (HttpServletRequest).

在答案中How to upload files to server using JSP/Servlet?此方法不会产生任何错误:

List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

最佳答案

如果我看到这里org.apache.commons.fileupload请求应该是 ServletRequestContext 而不是 HttpServletRequest :

List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(new ServletRequestContext(request));

关于java - 使用servlet和JSP上传文件时ServletFileUpload parseRequest()编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com