最近项目上有一个需求,用户上传文件后,要返回外部能直接的URL,查了些资料中与搞出来了,该需求的核心点是要将上传文件的路径暴露出来,便于外部通过URL直接访问,即将虚拟路径映射问文件系统的绝对路径
现将过程整理如下:
开发环境:SpringBoot2.0以上、JDK 1.8
1.修改spring boot配置文件信息如下
spring:
mvc:
static-path-pattern: /**
resources: #设置上传文件目录对外可见,这个参数很重要,不然上传文件对外是访问不到的
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${
serverInfo.uploadpath}
servlet:
multipart: #配置上传文件最大size
max-file-size: 100MB
max-request-size: 100MB
serverInfo: #配置上传文件磁盘存储路径
uploadpath: e:\uploadFile
2.上传文件代码
controller
@PostMapping("upload")
public ResultMsg uploadFile(Integer userId, MultipartFile file) {
long size = (long) file.getSize();
if (size > localConfig.getMaxFileSize()) {
return ResultMsg.getMsg("上传文件过大,请上传小于100MB大小的文件"