--使用依赖包
commons-fileupload-1.4.jar commons-io-2.6.jar hutool-all-5.2.3.jar
--html
文件上传测试 <form action="" method="post" enctype="multipart/form-data"> 名字<input type="text" id="username"> 文件<input type="file" id="filecontent"> <input type="button" value="提交" id="button_id"> </form>
--js
$("#button_id").click(() => { let formData = new FormData(); formData.append("name", $("#username").val()); formData.append("file", $("#filecontent")[0].files[0]) $.ajax({ url: "<%=request.getContextPath()%>/HasUserNameServlet", async: true, data: formData, success: function (res) { console.log(res) }, processData: false, //告诉jquery要传输data对象 contentType: false, type: "post", dataType: "json" }); });
--servlet
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.IdUtil; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; 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.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; @WebServlet("/HasUserNameServlet") public class HasUserNameServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 1.创建磁盘文件项工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); // 2.创建核心解析器对象 ServletFileUpload fileUpload = new ServletFileUpload(factory); // 3.解析request请求,返回list集合 List<FileItem> list = fileUpload.parseRequest(request); // 4.遍历list,获取上传项 for (FileItem fileItem : list) { // 5.判断是文件项还是普通项 if (fileItem.isFormField()) { // a.获取name属性 String name = fileItem.getFieldName(); // b.获取value属性 String value = fileItem.getString(); System.out.println("普通文本项:" + name + "=" + value); } else { // 上传文件项 // a.获取文件名 String filename = fileItem.getName(); // 获取上传文件扩展名 String extName = FileUtil.extName(filename); // 生成随机文件名 filename = IdUtil.simpleUUID() + "." + extName; // b.获取文件字节输入流 InputStream in = fileItem.getInputStream(); System.out.println("上传文件名:" + filename + ",上传文件流:" + in); // c.获取服务器upload目录真实路径... String realPath = request.getServletContext().getRealPath("/upload/"); // d.设置文件字节输出流 FileOutputStream out = new FileOutputStream(new File(realPath + filename)); // 流的copy IoUtil.copy(in, out); // 关流 out.close(); in.close(); response.getWriter().write("sucess"); } } } catch (Exception e) { e.printStackTrace(); } } }