springMvc文件上传:
1、文件上传
定义:就是将本地计算的中得文件上传到当前请求应用得应用服务器过程,称之为文件上传
2、springmvc中文件上传注意事项
a.准备文件上传页面 表单提交方式必须是post enctype必须是multipart/form-data
b.开发控制器咋控制器中使用MultipartFile形式进行接受用户上传文件
c.使用MultipartFile方式接受文件必须在配置文件中配置文件上传解析器 且 解析器得id必须为multipartResolver
d.multipartResolver 在处理文件上传是要求项目必须引入commons-fileupload
springboot中文件上传
1.准备上传页面 提供form表单 提交post emctype multipart/form-data
新建webapp:
这个文件是在main目录下新建得webapp中写的一个upload.jsp.
<%-- Created by IntelliJ IDEA. User: chenjl159 Date: 2020/8/19 Time: 15:02 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" isELIgnored="false" %> <html lang="en"> <head> <title>Title</title> </head> <body> <h1> 用来测试文件上传 </h1> <form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data"> <input type="file" name="aaa"> <br> <input type="submit" value="上传文件"> </form> </body> </html>
2.开发控制器 使用MultipartFile形式接受 将接受文件放入执行文件目录中即可
@Controller @RequestMapping("file") public class FileController { @RequestMapping("upload") public String upload(MultipartFile aaa, HttpServletRequest request) throws IOException { System.out.println("文件名"+aaa.getOriginalFilename()); System.out.println("文件类型"+aaa.getContentType()); System.out.println("文件大小"+aaa.getSize()); //根据相对获取绝对路径 String realPath = request.getSession().getServletContext().getRealPath("/files"); //创建时间文件夹 String format = new SimpleDateFormat("yyyy-MM--dd").format((new Date())); File file=new File(realPath,format); if(!file.exists()) file.mkdirs(); //获取文件后缀 String extension = FilenameUtils.getExtension(aaa.getOriginalFilename()); String newFileNamePrefix = UUID.randomUUID().toString().replace("-", "")+ new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); String newFileName =newFileNamePrefix+"."+extension; //处理上传操作 aaa.transferTo(new File(file,newFileName)); return "redirect:/upload.jsp"; } }
其中得配置文件:
server: port: 8989 servlet: context-path: /springboot_day2 jsp: #热部署 init-parameters: development: true spring: mvc: view: suffix: .jsp prefix: / servlet: multipart: max-request-size: 4MB #控制请求可以上传文件得大小大小 默认为10MB 单位可以为MB 和KB max-file-size: 4MB #真正用来控制实际文件上传大小限制 默认值为1MB 单位为MB #让max-file-size比max-request-size大或者相等较好,因为如果不行得话可以在请求得时候就拒绝,不在走后面得类型
目录结构: