index.jsp 上传文件页
uploaded.jsp 上传页
UploadFileServlet.java uploaded.jsp的Servlet,用于上传文件
1.index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Upload your file.</title>
</head>
<body>
<form action="/uploaded.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" value="Submit">Submit</button>
<button type="reset" value="Reset">Reset</button>
</form>
</body>
</html>
- uploaded.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Upload!</title>
</head>
<body>
</body>
</html>
- UploadFileServlet.java
package lh.upload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(name = "UploadServlet", urlPatterns = "/uploaded.jsp")
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(request)) {
PrintWriter writer = response.getWriter();
writer.println("Error: enctype=multipart/form-data");
writer.flush();
return;
}
// 以下6行代码记住就好
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setSizeThreshold(1024 * 1024 * 3); // 30 MB
diskFileItemFactory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
fileUpload.setFileSizeMax(1024 * 1024 * 30); //文件最大为30MB
fileUpload.setSizeMax(1024 * 1024 * 50);
String fileUploadPath = getServletContext().getRealPath("./") + File.separator + "uploads";
// 文件存放路径
File uploadFileDir = new File(fileUploadPath);
// 判断文件夹是否存在
if (!uploadFileDir.exists()) {
uploadFileDir.mkdir();
}
try {
@SuppressWarnings("unchecked")
List<FileItem> fileItemList = fileUpload.parseRequest(new ServletRequestContext(request));
// 遍历文件列表并上传
if (fileItemList != null && fileItemList.size() > 0) {
for (FileItem item : fileItemList) {
String fn = new File(item.getName()).getName();
String fp = fileUploadPath + File.separator + fn;
File storeFile = new File(fp);
System.out.println(fp);
item.write(storeFile);
request.setAttribute("resMsg", "OK");
}
}
} catch (Exception ex) {
request.setAttribute("exMsg", ex.getMessage());
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}