springboot的文件上传和基本的文件上传操作一样,简化了非常多的操作,使用起来非常的简单,想知道实现原理的可以看我的另一篇博客
1.先写一个文件上传的form表单这里的enctype必须改成multipart/form-data
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/file" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传文件">
</form>
</body>
</html>
2.在后台处理下文件,记得在D盘下创建uploaded文件夹
package com.xx.controller;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@RequestMapping("/file.html")
public String fileHTML() {
return "file";
}
//获取配置文件中的文件存储地址
@Value("${file.path}")
private String path;
//文件上传,springboot制定了默认的单个文件大小和每次上传的文件大小,可以在配置文件中自定义文件大小
@PostMapping("/file")
public void file(MultipartFile file) throws FileNotFoundException, IOException {
//设置文件存储地址,文件存储地址写死在这里不太合适,这里选择写在配置文件中动态获取
//String path = "D:\\uploaded\\";
//获取原始文件名,使用原始文件名容易造成文件重名,所以一般会自定义文件名
//String fileName = file.getOriginalFilename();
//这里选择时间作为文件名
String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//获取文件后缀名
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//使用spring提供的文件拷贝工具类
FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(path+fileName+suffix));
}
}
3.修改配置文件,这个可以不修改springboot提供了默认的文件上传配置
#单个文件最大尺寸
spring.servlet.multipart.max-file-size=10MB
#一个请求最大尺寸
spring.servlet.multipart.max-request-size=50MB
#自定义文件上传目录
file.path=d:/uploaded/