在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
頁面。