文件上传
1. 导入jar包,这里还要导入servlet api
2. 编写servlet
@WebServlet("/upFile") public class UpLoad extends HttpServlet { // 上传文件存储目录 private static final String UPLOAD_DIRECTORY = "upload"; // 上传配置 // 3MB private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 40MB private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 50MB private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if(!ServletFileUpload.isMultipartContent(req)){ /** * 可以添加提示信息 */ return; } ServletFileUpload upload = this.getUpload(); this.upload(upload); // 构造临时路径来存储上传的文件 // 这个路径相对当前应用的目录 String uploadPath = req.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY; File filePath = new File(uploadPath); if(!filePath.exists()){ filePath.mkdirs(); } try { List<FileItem> formItems = upload.parseRequest(req); if(formItems!=null&&formItems.size()>0){ for (FileItem item : formItems) { System.out.println("item.getName()::"+item.getName()); //String fileName = new File(item.getName()).getName(); if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String path = uploadPath + File.separator + fileName; File storeFile = new File(path); // 在控制台输出文件的上传路径 System.out.println(filePath); // 保存文件到硬盘 item.write(storeFile); req.setAttribute("message","文件上传成功!"); } } } } catch (Exception e) { e.printStackTrace(); } } //获取ServletFileUpload public ServletFileUpload getUpload(){ // 配置上传参数 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中 factory.setSizeThreshold(MEMORY_THRESHOLD); // 设置临时存储目录 factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); return upload; } public void upload(ServletFileUpload upload){ // 设置最大文件上传值 upload.setFileSizeMax(MAX_FILE_SIZE); // 设置最大请求值 (包含文件和表单数据) upload.setSizeMax(MAX_REQUEST_SIZE); // 中文处理 upload.setHeaderEncoding("UTF-8"); } }
3. 前台代码
form的method必须设置为post 必须添加enctype属性,这样form表单会把数据以二进制的形式传输
<body> <form action="${pageContext.request.contextPath}/upFile" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="提交"> </form> </body>