enctype="multipart/form-data" 並包含 <input type="file" name="uploadFile">。@MultipartConfig 註解(Servlet 3.0+)或手動解析 request.getInputStream()。request.getPart("uploadFile") 取得 Part 物件。part.getInputStream() 讀取檔案流,或 part.write(path) 直接儲存。<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" />
<input type="submit" value="上傳" />
</form>
@WebServlet("/UploadServlet")
@MultipartConfig(
fileSizeThreshold = 1024 * 1024, // 1 MB 臨時存儲閾值
maxFileSize = 1024 * 1024 * 10, // 10 MB 單檔上限
maxRequestSize = 1024 * 1024 * 50 // 50 MB 總請求上限
)
public class UploadServlet extends HttpServlet {
private static final String UPLOAD_DIR = "uploads";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 取得 Part
Part filePart = request.getPart("uploadFile");
if (filePart == null || filePart.getSize() == 0) {
response.getWriter().println("未選擇檔案");
return;
}
// 取得檔名(需處理瀏覽器差異)
String fileName = getFileName(filePart);
String applicationPath = getServletContext().getRealPath("");
String uploadPath = applicationPath + File.separator + UPLOAD_DIR;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) uploadDir.mkdirs();
String filePath = uploadPath + File.separator + fileName;
try (InputStream fileContent = filePart.getInputStream();
FileOutputStream fos = new FileOutputStream(filePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileContent.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
response.getWriter().println("上傳成功:" + filePath);
}
}
// 從 Content-Disposition header 解析檔名
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
for (String token : contentDisp.split(";")) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf('=') + 2, token.length() - 1);
}
}
return "unknown";
}
}
@MultipartConfig 與 getPart()。fileSizeThreshold 避免記憶體溢位,超過閾值會寫入臨時檔案。.., /, \)。Apache Commons FileUpload 或 Spring MVC 封裝,更健壯。詳細原始碼與解析:CSDN - Servlet 3.0 檔案上傳完整範例