前言
今天在帮朋友看文件上传问题的时候,发现上传的文件虽然上传到本地路径或者项目文件下了,但是访问却访问不到,要重新启动项目才可以。
找了下网上的解决方案,不一而足,在此收集我试了可以用的方案
文件存储在编译文件下
按下面这个代码可以将文件存在编译文件下 ,也就是target/classes下面
String path = "/static/upload/"; File file1 = null; try { file1 = new File(ResourceUtils.getURL("classpath:").getPath()); } catch (FileNotFoundException e) { // nothing to do } if (file1 == null || !file1.exists()) { file1 = new File(""); } String savePath = file1.getAbsolutePath()+path;
不过这样并没有存储在项目下,所以项目如果clean一下那么这些文件将都会消失,不过对与某些项目来说只有开始和停止,也并没有重新部署的必要。
或者完全可以利用这一特点,存储临时文件,项目重新编译时文件消失。
配置访问虚拟路径
文件实际是存在e盘的path路径下面,但是当访问http://ip:port/upload/xxx.jpg时,虚拟路径会映射到file://e:/path/xxx.jpg的路径中访问文件。也是对服务器文件的一种保护措施吧.
启动类集成WebMvcConfigurationSupport
@SpringBootApplication public class DemoApplication extends WebMvcConfigurationSupport { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { System.out.println("config启动了"); //项目路径 //String savePath = "\\src\\main\\resources\\static\\upload\\"; //String path = System.getProperty("user.dir")+savePath; //本地路径 String path = "e:/path/"; registry.addResourceHandler("/upload/**").addResourceLocations("file:"+path); } }
实现配置类WebMvcConfigurer
@Configuration public class MyPicConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { System.out.println("config启动了"); //项目路径 //String savePath = "\\src\\main\\resources\\static\\upload\\"; //String path = System.getProperty("user.dir")+savePath; //本地路径 String path = "e:/path/"; registry.addResourceHandler("/upload/**").addResourceLocations("file:"+path); } }