SpringBoot 文件访问配置虚拟路径

191 阅读1分钟

这个是上传的代码

if (!bannerDetailDto.getMultipartFile().isEmpty()){
    UUID uuid = UUID.randomUUID();
    String strUuId = uuid.toString();
    String fileName = bannerDetailDto.getMultipartFile().getOriginalFilename();
    fileUrl = basePath + strUuId + fileName;  //basePath 是@Value进来的 一个死路径
    try {
        bannerDetailDto.getMultipartFile().transferTo(new File(fileUrl));
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        fileUrl = "/upload/" + strUuId + fileName; // 最后存到数据库的一个实际路径
    }
}
// fileUrl = "/upload" + uuid + 文件名  最后是一个字符串

最后我会把fileUrl存到我的数据库里

但是你这样你前端是访问不到的

接下来就是搞定这个配置虚拟路径了

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**") //第一个是你的虚拟路径
                .addResourceLocations("file:///D:/miniipoupload/"); //这个是你的死路径
    }
}

如果你的控制器controller是get请求、前端只需要通过拼接ip和端口 访问虚拟路径以及后面的文件名,就可以在浏览器打开了

简单来说 就是把你的死路径 映射成一个你命名的在浏览器地址栏的一个路径,然后前端就可以获取了,不让在浏览器上些什么d盘啥的就很low了