jakarta Servlet cannot use ServletFileUpload.parseRequest() to convert HttpRequest obj to List obj [duplicate]
原创文章,禁止私自转载 / Original article, private reproduction prohibited
The situation at the time I encountered the problem.
full code:
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.*;
import java.util.List;
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
// set Content-Type
resp.setHeader("Content-type", "text/html;charset=UTF-8");
// create DiskFileItemFactory object
DiskFileItemFactory factory = new DiskFileItemFactory();
// set file temporary storage path, if the path does not exist, create it
factory.setRepository(new File("D:\\source\\jsp\\fileupdown\\temp"));
if (!factory.getRepository().exists()) {
factory.getRepository().mkdirs();
}
// set ServletFileUpload object
ServletFileUpload upload = new ServletFileUpload(factory);
// set character encoding
upload.setHeaderEncoding("UTF-8");
// analyze request, get file item list
List<FileItem> fileitems = upload.parseRequest(req);
// get byte stream
PrintWriter writer = resp.getWriter();
// traverse file item list
for (FileItem fileitem : fileitems) {
// if it is a form field
if (fileitem.isFormField()) {
// get field name
String name = fileitem.getFieldName();
if (name.equals("name")) {
if (fileitem.getString("UTF-8").equals("")) {
writer.println("name can not be empty");
} else {
writer.println("name:" + fileitem.getString("UTF-8"));
}
}
} else {
// get file name
String filename = fileitem.getName();
// process file
if (filename != null && !filename.equals("")) {
writer.print("uploaded file:" + filename + "<br>");
filename = filename.substring(filename.lastIndexOf("\\") + 1);
// unique file name
String uniqueFileName = System.currentTimeMillis() + "_" + filename;
// create same name file in server
String webPath = "/upload/";
String realPath = getServletContext().getRealPath(webPath + uniqueFileName);
// create file
File file = new File(realPath);
file.getParentFile().mkdirs();
file.createNewFile();
// get UploadStream
InputStream in = fileitem.getInputStream();
// use FileOutputStream to write file
FileOutputStream out = new FileOutputStream(file);
// create buffer
byte[] buffer = new byte[1024];
int len = 0;
// read file
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
writer.println("upload successfully");
} else {
writer.println("file can not be null");
}
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
}
}
}
the error:
java: Cannot access javax.servlet.http.HttpServletRequest
Cannot find class file of javax.servlet.http.HttpServletRequest
the code that reports the error:
// set ServletFileUpload object
ServletFileUpload upload = new ServletFileUpload(factory);
// set character encoding
upload.setHeaderEncoding("UTF-8");
// analyze request, get file item list
List<FileItem> fileitems = upload.parseRequest(req);
I have tried to rewrite the code as follows, but it still cannot work.
// set ServletFileUpload object
ServletFileUpload upload = new ServletFileUpload(factory);
// set character encoding
upload.setHeaderEncoding("UTF-8");
// analyze request, get file item list
List<FileItem> fileitems = upload.parseRequest((RequestContext) req);
How to fix the problem?
I found that this was caused by the fact that the source code on the net about servlet implementation of file download was out of date. So we should try to use our servlet code with the current state of technology.
And here’s my new code to implement the function of file download.
jsp/html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传下载</title>
</head>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<table style="width: 600px">
<tr>
<td>username</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>file</td>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td><input type="submit" name="upload"/></td>
</tr>
</table>
</form>
</body>
</html>
servlet
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
@WebServlet(name = "UploadServlet",
value = "/UploadServlet",
initParams = {
@WebInitParam(name = "upload_location", value = "D:\\source\\jsp\\fileupdown\\uploadfiles")
})
@MultipartConfig
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
// set Content-Type
resp.setHeader("Content-type", "text/html;charset=UTF-8");
// get file stream
String name = req.getParameter("name"); // Retrieves <input type="text" name="name">
Part filePart = req.getPart("file"); // Retrieves <input type="file" name="file">
if (filePart == null){
resp.getWriter().print("please choose a file");
return;
}
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
// save file
File uploads = new File(getServletConfig().getInitParameter("upload_location"));
File file = new File(uploads, fileName);
try (InputStream input = filePart.getInputStream()) {
Files.copy(input, file.toPath());
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ServletException e) {
throw new RuntimeException(e);
}
}
}
One thing to look out for in the code:
Remember to add @MultipartConfig
in front of this your servlet, or you will receive null in Part filePart = req.getPart("file");
.
Reference:
java – How can I upload files to a server using JSP/Servlet? – Stack Overflow
tomcat – Recommended way to save uploaded files in a servlet application – Stack Overflow