- 在页面上面,form 表单里面添加属性enctype="multipart/form-data"
比如:
<form name="frm" method="post" enctype="multipart/form-data">
- 添加文件选择框:
<input type="file" name="uploadFile">
- 添加上传文件需要的包:
FileUpload – Download Apache Commons FileUpload
commons-fileupload-1.4.jar
以及依赖包:
commons-io-2.2.jar
- 编写代码:
在homepage.jsp页面: <form name="frm" method="post" action="/user/uploadpicture" enctype="multipart/form-data"> <input type="file" name="uploadFile"><br> <input type="submit" value="上传"> </form> 然后添加一个servlet处理上传文件 package com.hwadee.train.servlet;
import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; 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.util.List;
@WebServlet("/user/uploadpicture") public class UserUploadPictureServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { System.out.println("测试:UserUploadPictureServlet doPost"); // 这个路径相对当前应用的目录 String uploadPath = req.getServletContext().getRealPath("./") + File.separator + "upload"+ File.separator +"imgs"; // 如果目录不存在则创建 File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } // 配置上传参数 DiskFileItemFactory factory = new DiskFileItemFactory(); // // 设置临时存储目录 // factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); try { // 解析请求的内容提取文件数据 @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(req); if (formItems != null && formItems.size() > 0) { // 迭代表单数据 for (FileItem item : formItems) { // 处理不在表单中的字段 if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // 在控制台输出文件的上传路径 System.out.println(filePath); // 保存文件到硬盘 item.write(storeFile); } } } } catch (Exception ex) { req.setAttribute("message", "错误信息: " + ex.getMessage()); } resp.sendRedirect("/homepage.jsp"); } } |