1.在index.jsp编写如下代码:
<%-- Created by IntelliJ IDEA. User: Adair Date: 2020/7/2 0002 Time: 16:07 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>首页</title> </head> <body> <h3>传统文件上传</h3> <form action="/file/fileUpload01" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="upload" /><br/> <input type="submit" value="上传" /> </form> </body> </html> 创建文件上传控制器类控制器类的代码如下: package com.txw.controller; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.List; import java.util.UUID; /** * 文件上传的处理类 * @author Adair */ @Controller @RequestMapping(path = "/file") @SuppressWarnings("all") // 注解警告信息 public class FileUploadController { /** * 文件上传 * @return */ @RequestMapping(path = "/fileUpload01") public String fileUpload01(HttpServletRequest request) throws Exception{ System.out.println("文件上传"); // 使用fileupload组件完成文件上传 // 上传的位置 String path = request.getSession().getServletContext().getRealPath("/uploads/"); System.out.println(path); // 判断,该路径是否存在 File file = new File(path); if(!file.exists()){ // 创建该文件夹 file.mkdirs(); } // 解析request对象,获取上传文件项 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // 解析request List<FileItem> items = upload.parseRequest(request); // 遍历文件项 for(FileItem item:items){ // 进行判断,当前item对象是否是上传文件项 if(item.isFormField()){ // 说明普通表单向 }else{ // 说明上传文件项 // 获取上传文件的名称 String filename = item.getName(); // 把文件的名称设置唯一值,uuid String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid+"_"+filename; // 完成文件上传 item.write(new File(path,filename)); // 删除临时文件 item.delete(); } } return "success"; } }3.使用TomCat运行结果如图: 4.通过浏览器访问http://localhost:8080/index.jsp结果如图所示: 5.点击上传会跳转到如图所示的界面: 6.控制台打印结果如图所示: 7.查看上传的文件如图所示: