简介:讲解HTML页面文件上传和后端处理实战
1:什么是MultipartFile
? MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。
2:什么是transferTo
? MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)
使用transferTo (本质上还是使用了流 只不过是封装了步骤) ,会生成文件,最后不需要文件要删除
3.MultipartFile类常用的一些方法:
- String getContentType() //获取文件MIME类型
- InputStream getInputStream() //后去文件流
- String getName() //获取表单中文件组件的名字
- String getOriginalFilename() //获取上传文件的 原名
- long getSize() //获取文件的字节大小,单位byte
- boolean isEmpty() //是否为空
- void transferTo(File dest) //保存到一个目标文件中。
4.Multipartfile与File类型相互转换
特殊情况下需要做转换
1、Multipartfile转File
1 2 3 | File file = new File(path); FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file); |
2、File转Multipartfile
1 2 3 4 5 | File file = new File("src/test/resources/input.txt"); FileInputStream input = new FileInputStream(file); MultipartFile multipartFile =new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input)); |
5.springboot2.x版本设置上传文件大小的两种方式
-
在配置类中配置@Bean,注意当前配置类上需要加注解@Configuration
也可以在启动类直接注入@Bean方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package com.beiluo.demo.config; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.unit.DataSize; import org.springframework.util.unit.DataUnit; import javax.servlet.MultipartConfigElement; @Configuration public class FileConfig { @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); //文件最大10M,DataUnit提供5中类型B,KB,MB,GB,TB factory.setMaxFileSize(DataSize.of(10, DataUnit.MEGABYTES)); /// 设置总上传数据总大小10M factory.setMaxRequestSize(DataSize.of(10, DataUnit.MEGABYTES)); return factory.createMultipartConfig(); } } |
-
配置文件直接配置 max-file-size 是单个文件大小 max-request-size是设置总上传的数据大小
- application.properties
1
2
3
4
5
6
7
8
9
10
11
12#是否开启文件上传支持,默认是true
spring.servlet.multipart.enabled=true
#文件写入磁盘的阈值,默认是0
spring.servlet.multipart.file-size-threshold=0
#上传文件的临时保存位置
spring.servlet.multipart.location=D:\\upload
#单个文件的最大值,默认是1MB
spring.servlet.multipart.max-file-size=1MB
#多个文件上传时的总大小 值,默认是10MB
spring.servlet.multipart.max-request-size=10MB
#是否延迟解析,默认是false
spring.servlet.multipart.resolve-lazily=false- application.yml
1 2 3 4 5 | spring: servlet: multipart: max-file-size: 10MB max-request-size: 10MB |
6.单文件上传
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | package com.beiluo.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.UUID; @Controller public class FileController { //上传路径 private static final String filePath = "G:\\javaDemo\\demo\\src\\main\\resources\\upload\"; @RequestMapping(value = "/api/index") public Object index() { return "success"; } @RequestMapping(value = "upload") @ResponseBody public String upload(@RequestParam("myfile") MultipartFile file, HttpServletRequest request) { String content = request.getParameter("content"); System.out.println("备注:" + content); //获取文件名 String fileName = file.getOriginalFilename(); System.out.println("上传的文件名为:" + fileName); //获取文件的后缀名 ,比如图片的jpeg,png String suffixName = fileName.substring(fileName.lastIndexOf(".")); System.out.println("上传的文件后缀名为:" + suffixName); //文件上传后的路径 fileName = UUID.randomUUID() + suffixName; System.out.println("转化后的名称" + fileName); File newFile = new File(filePath + fileName); try { file.transferTo(newFile); return "<p style="color: green"> 上传成功!</p>"; } catch (Exception e) { e.printStackTrace(); } return "上传失败"; } } |
html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> <!--<script src="/js/file.js" type="text/javascript"></script>--> </head> <body> <div> 测试文件上传! </div> <form enctype="multipart/form-data" method="post" action="/upload"> 文件:<input type="file" name="myfile"> 备注:<input type="text" name="content"> <input type="submit" value="提交"> </form> </body> </html> |
4.多文件上传
html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>多文件上传</title> </head> <body> <form action="/uploads" method="post" enctype="multipart/form-data"> <input type="file" name="uploadFiles" value="请选择文件" multiple> <input type="file" name="uploadFiles" value="请选择文件" multiple> <input type="file" name="uploadFiles" value="请选择文件" multiple> <input type="submit" value="上传"> </form> </body> </html> |
java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/"); @RequestMapping("/uploads") @ResponseBody public String upload(MultipartFile[] uploadFiles, HttpServletRequest request) { List list = new ArrayList();//存储生成的访问路径 if (uploadFiles.length > 0) { for (int i = 0; i < uploadFiles.length; i++) { MultipartFile uploadFile = uploadFiles[i]; //设置上传文件的位置在该项目目录下的uploadFile文件夹下,并根据上传的文件日期,进行分类保存 String realPath = request.getSession().getServletContext().getRealPath("uploadFile"); String format = sdf.format(new Date()); File folder = new File(realPath + format); if (!folder.isDirectory()) { folder.mkdirs(); } String oldName = uploadFile.getOriginalFilename(); System.out.println("oldName = " + oldName); String newName = UUID.randomUUID().toString() + oldName. substring(oldName.lastIndexOf("."), oldName.length()); System.out.println("newName = " + newName); try { //保存文件 uploadFile.transferTo(new File(folder, newName)); //生成上传文件的访问路径 String filePath = request.getScheme() + "://" + request.getServerName() + ":"+ request.getServerPort() + "/uploadFile" + format + newName; list.add(filePath); } catch (IOException e) { e.printStackTrace(); } } return list.toString(); } else if (uploadFiles.length == 0) { return "请选择文件"; } return "上传失败"; } |
多文件上传参考链接 https://blog.csdn.net/Shu2018ai/article/details/97625191