建立一个springboot项目,并添加spring-boot-starter-web依赖。
然后在resources目录下的static文件夹下创建一个upload.html文件,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="uploadFile" value="请选择文件">
<input type="submit" value="上传">
</form>
</body>
</html>
这是一个很简单的上传页面,上传接口是"/upload",请求方法是post,enctype是multipart/form-data,
然后创建文件上传的接口,代码如下:
@RestController
public class FileUploadController {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
@RequestMapping("/upload")
public String upload(MultipartFile uploadFile, HttpServletRequest request) {
//设置上传文件的位置在该项目目录下的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;
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
然后启动项目,在浏览器中测试,输入"http://localhost:8080/upload.html".
文件上传的常见配置:
#是否开启文件上传支持,默认是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