ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 要求 1. form表单的enctype取值必须是multipart/form-data(默认值是application/x-www-form-urlencoded). enctype:是表单请求正文的类型. 2. emthod必须是post. 3. 提供一个文件选择域. ## 原理分析 ![](https://box.kancloud.cn/994c3d28652537df943048f83cd24f01_834x226.png) ## 传统文件上传方式 导入依赖: ~~~ <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> ~~~ ~~~ <form action="/spring/upload" method="post" enctype="multipart/form-data"> <input type="file" name="upload"> <input type="submit"> </form> ~~~ ~~~ @RequestMapping(path = "/upload") public String testResponse(HttpServletRequest request, HttpServletResponse response) throws Exception { //使用fileupload组件完成上传 String realPath = request.getSession().getServletContext().getRealPath("/uploads/"); //判断该路径是否存在 File file = new File(realPath); if (!file.exists()) { //创建文件夹 file.mkdirs(); } //获取request对象,获取文件项 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); //解析request List<FileItem> fileItems = upload.parseRequest(request); //遍历 for (FileItem fileItem : fileItems) { //判断当前item对宪法是否 是上传文件项 if (fileItem.isFormField()) { //普通表单项 } else { //上传文件项 //获取文件的名称 String filename = fileItem.getName(); //把文件名设为唯一 String s = UUID.randomUUID().toString().replace("-", ""); filename = s + "_" + filename; //完成文件上传 fileItem.write(new File(realPath, filename)); //删除临时文件 fileItem.delete(); System.out.println("成功"); } } return "success"; } ~~~