在Java Web中处理文件上传通常涉及到以下几个步骤:
enctype
属性设置为multipart/form-data
,这是处理文件上传所必需的。<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
HttpServletRequest
对象来获取上传的文件,并使用Part
对象来处理文件的元数据和内容。import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/upload")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class FileUploadServlet extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "uploads";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = getSubmittedFileName(filePart);
String filePath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
try (InputStream fileContent = filePart.getInputStream();
OutputStream out = new FileOutputStream(new File(filePath + File.separator + fileName))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileContent.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
// Handle the exception appropriately in your application
}
response.sendRedirect("success.jsp");
}
private String getSubmittedFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
}
web.xml
文件中配置Servlet。<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.example.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
<!DOCTYPE html>
<html>
<head>
<title>File Upload Success</title>
</head>
<body>
<h1>File uploaded successfully!</h1>
</body>
</html>
现在,当用户通过HTML表单上传文件时,FileUploadServlet
将处理文件并将其保存到服务器的uploads
目录中。文件上传成功后,用户将被重定向到success.jsp
页面。