简体   繁体   English

ServletFileUpload#parseRequest(request) 中的错误与 tomcat 10

[英]Error in ServletFileUpload#parseRequest(request) with tomcat 10

Working on a simple file upload program.开发一个简单的文件上传程序。 I had to use jakarta.servlet.* classes as I am using Tomcat v10.我必须使用 jakarta.servlet.* 类,因为我使用的是 Tomcat v10。 I am getting compile time error on parseRequest(request) line.我在 parseRequest(request) 行上收到编译时错误。

Code:代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        ServletFileUpload sf = new ServletFileUpload(new DiskFileItemFactory());
        try {
            List<FileItem> multifiles = sf.parseRequest(request);
            
            for(FileItem i : multifiles) {
                i.write(new File("C:/Users/Luffy/Documents/FileUploadDemo/"+i.getName()));
            }
            response.getWriter().print("The file is uploaded");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        response.getWriter().print("The file is uploaded");
    }

The error is as below:错误如下:

The method parseRequest(javax.servlet.http.HttpServletRequest) in the type ServletFileUpload is not applicable for the arguments (jakarta.servlet.http.HttpServletRequest) ServletFileUpload 类型中的 parseRequest(javax.servlet.http.HttpServletRequest) 方法不适用于 arguments (jakarta.servlet.Z80791B3AE7002CB88C246876D9FAA8)

I searched a lot on google but couldn't find a solution.我在谷歌上搜索了很多,但找不到解决方案。

Please suggest a workaround or possible solution.请提出解决方法或可能的解决方案。 Thanks in advance.提前致谢。

This is my first post in Stack overflow.这是我在堆栈溢出中的第一篇文章。 So ignore my mistakes if any:)所以忽略我的错误,如果有的话:)

You are trying to use the ServletFileUpload class from commons-fileupload , which doesn't work with a jakarta.servlet.http.HttpServletRequest .您正在尝试使用commons-fileupload中的ServletFileUpload class ,它不适用于jakarta.servlet.http.HttpServletRequest The library must be adapted to work with Servlet 5.0 classes.该库必须适用于 Servlet 5.0 类。

Fortunately since Servlet 3.0 (Tomcat 8.0) multipart/form-data requests can be parsed by the servlet.幸运的是,由于 Servlet 3.0 (Tomcat 8.0) multipart/form-data请求可以由 servlet 解析。 You just need to:你只需要:

try {
    final Collection<Part> parts = request.getParts();
    for (final Part part : parts) {
       part.write("C:/Users/Luffy/Documents/FileUploadDemo/"+part.getSubmittedFileName());
    }
    response.getWriter().print("The file has been uploaded successfully.");
} catch (Exception e) {
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Upload failed.");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM