SpringBoot实现文件上传
1. 配置文件上传限制
application.yml
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
2. 创建文件上传控制器
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.UUID;
@RestController
public class FileController {
//文件上传管理
@PostMapping("/uploadFile")
public String uploadFile(MultipartFile[] files){
for(MultipartFile file:files){
// 获取文件名以及后缀名
String fileName = file.getOriginalFilename();
// 重新生成文件名(根据具体情况生成对应文件名)
fileName = UUID.randomUUID()+"_"+fileName;
// 指定上传文件本地存储目录,不存在需要提前创建
String dirPath = "D:/file/";
File filePath = new File(dirPath);
if(!filePath.exists()){
filePath.mkdirs();
}
try {
file.transferTo(new File(dirPath+fileName));
return "上传成功";
} catch (Exception e) {
e.printStackTrace();
}
}
return "上传失败";
}
}
3. 创建文件上传页面
在src/main/resources/backend
目录下创建upload.html文件
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件上传</title>
</head>
<body>
<form action="/uploadFile" method="post" enctype="multipart/form-data" >
<input type="file" name="files"> <br> <br>
<input type="submit" value="提交" >
</form>
</body>
</html>
这里backend目录事先有做了静态资源映射:自定义静态资源的映射
4. 运行测试
运行Spring Boot项目并访问http://127.0.0.1:8080/backend/upload.html
。选择文件并点击“提交”按钮,文件将被上传到指定的目录(在这个例子中是D:/file/
)。
查看上传目录
如果需要把上传文件(图片)能通过http请求显示出来,需要做静态资源映射(自定义静态资源的映射)。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
registry.addResourceHandler("/images/**").addResourceLocations("file:D:/file/");
}
}
配置完成后访问http://127.0.0.1:8080/images/
目录下的指定图片(文件)。