1.新创建一个Mav项目需要包含SpringWeb的依赖即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.需要在application.properties配置数据库相关数据
#添加静态文件路径
spring.web.resources.static-locations=file:F:/files,classpath:static
#连接数据库
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/weibo?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
#设置文件上传大小的限制
spring.servlet.multipart.max-file-size=10MB
3.在staitc新建一个upload.html的前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" value="请选择文件">
<input type="submit" value="上传">
</form>
</body>
</html>
4.创建文件上传处理的接口
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author 龙御修
* @create 2022-05-18 23:02
*/
@RestController
public class FileUploadController {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
@PostMapping("/upload")
public String upload(MultipartFile uploadFile, HttpServletRequest req){
String realPath=req.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();
String newName= UUID.randomUUID().toString()+
oldName.substring(oldName.lastIndexOf("."),oldName.length());
//防止文件重名
try {
uploadFile.transferTo(new File(folder,newName));
String filePath= req.getScheme()+"://"+req.getServerName()+":"+
req.getServerPort()+"/uploadFile/"+format+newName;
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
5.在浏览器中输入http://localhost:8080/upload.html
6.上传文件,浏览器可以看见地址就OK了
其他配置
#开启文件上传支持,默认为true
spring.servlet.multipart.enabled=true
#文件写入磁盘的阈值,默认为0
spring.servlet.multipart.file-size-threshold=0
#添加静态文件路径
spring.web.resources.static-locations=file:F:/files,classpath:static
#设置文件上传大小的限制
spring.servlet.multipart.max-file-size=10MB
#表示多文件上传时文件的总大小,默认为10MB
spring.servlet.multipart.max-request-size=10MB
#表示文件是否延迟解析,默认为false
spring.servlet.multipart.resolve-lazily=false