SpringMVC - CommonsMultipartResolver 文件上传
第一步 导包
<!--文件上传组件--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
第二步 配置 springMVC.xml
<!--文件上传解析器--> <!--id或 name 名必须为 :multipartResolver--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 单位 :byte --> <property name="maxUploadSize" value="102400"/> </bean>
第三步编写 前端页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <!-- 设置 enctype= "multipart/form-data" --> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传文件"> </form> </body> </html>
第四步 编写 Controller
package com.www.fileupload; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.UUID;
/** * @author Www * @version 11.0.9 * @create 2022/3/14 14:19 星期一 * @since 16 */ @Controller @RequestMapping("upload") public class UploadController { @RequestMapping("file") public String toUpload(MultipartFile file, Map<String, String> map) throws IOException { // 获取 源文件的名称 String filename = file.getOriginalFilename(); System.out.println("filename = " + filename); assert filename != null; // 获取后缀名 String subFileName = filename.substring(filename.lastIndexOf(".")); System.out.println("subFileName = " + subFileName); // UUID UUID uuid = UUID.randomUUID(); // 把文件按照日期进行分类 //获取 当当前日期 Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); // 日期文件名 String dataFileName = simpleDateFormat.format(date); System.out.println("dataFileName = " + dataFileName); // 创建文文件目录 File dataFile = new File("D:/upload/" + dataFileName); String fileName = uuid + subFileName; // 判断文件夹是否存在 if (!dataFile.exists()) { dataFile.mkdirs(); //当文件不存在时创建文件 } // 上传文件 file.transferTo(new File("D:/upload/" + dataFileName + "/" + fileName)); map.put("dataFileName",dataFileName); map.put("fileName",fileName); return "avatar"; } }
第四步 添加访问路径
第五步 测试
第六步 图片回显
在 tomcat 设置虚拟路路径
创建 回显页面 ,并设置访问路经
<%-- Created by IntelliJ IDEA. User: Www Date: 2022/3/14 Time: 15:03 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>头像显示</title> </head> <body> <img src="/upload/${dataFileName}/${fileName}" alt="头像"> </body> </html>
