1. 文件上传表单(upload.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
选择文件: <input type="file" name="file" /><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
2. 处理文件上传的Servlet(FileUploadServlet.java):
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
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("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold = 1024 * 1024, // 1 MB
maxFileSize = 1024 * 1024 * 5, // 5 MB
maxRequestSize = 1024 * 1024 * 5 * 5) // 25 MB
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// 获取上传文件的保存路径
String savePath = getServletContext().getRealPath("/") + "uploads";
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
PrintWriter out = response.getWriter();
try {
// 处理文件上传
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}
out.println("<h3>文件上传成功</h3>");
} catch (Exception e) {
out.println("<h3>文件上传失败</h3>");
out.println("<p>" + e.getMessage() + "</p>");
} finally {
out.close();
}
}
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return "";
}
}
在上述例子中,文件将被保存到服务器上的 "uploads" 目录中。确保你的服务器有写入权限,并且你可能需要根据实际需求修改文件的保存路径和大小限制。
转载请注明出处:http://www.pingtaimeng.com/article/detail/13675/JSP