【SpringBoot新手篇】springboot 文件上传虚拟路径设置
问题
在做文件上传是使用String path = ResourceUtils.getURL("classpath:").getPath();
或者 String realPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
获取上传路径的时候是target目录下,也就是说,只要target目录没了,文件也就没了,这个是我们不想看到的。还有一种经常使用的方式就是直接将上传文件存到磁盘中,但是我们在前端却不能直接引用磁盘里的真实路径的文件,因为这个存在安全问题,所以这个时候,我们就要用web服务器来帮我们做一个虚拟映射,我们访问一个虚拟路径,其实访问的就是本机的真实路径,这样保证了安全性。
yml配置访问路径
file:
###静态资源对外暴露的访问路径
staticAccessPath: /api/file/**
###静态资源实际存储路径
uploadFolder: G:/staticResource/upload/
设置虚拟路径,访问绝对路径下资源
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${file.uploadFolder}")
private String uploadFolder;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
}
}
controller
@Value("${file.uploadFolder}")
private String uploadFolder;
@PostMapping("/project/upload/{id}")
public ResultVO<?> fileupload(MultipartFile file, HttpServletRequest req,@PathVariable Long id) throws FileNotFoundException {
//使用UUID生成唯一标识文件名
String randomNumber = UUID.randomUUID().toString().replace("-", "");
//获取文件的原始名
String oldFilename = file.getOriginalFilename();
//获取文件后缀 .pdf
String extension = oldFilename.substring(oldFilename.lastIndexOf("."));
//生成新的文件名
String newFileName = randomNumber + extension;
File dateDir = new File(uploadFolder);
if (!dateDir.exists()) {
//判断目录是否存在,不存在则直接创建
dateDir.mkdirs();
}
try {
file.transferTo(new File(dateDir, newFileName));
} catch (IOException e) {
e.printStackTrace();
return ResultVO.fail("上传失败");
}
//上传完毕,可以把上传地址保存到数据库或者直接返回前端显示
String invented_address = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() + "/api/file/" + newFileName;
Project project = new Project();
project.setId(id);
project.setInterfaceDocUrl(invented_address);
projectService.updateById(project);
return ResultVO.ok("上传成功");
}