前台是vue项目,需要在使用过程中访问已上传的本地文件。
访问地址为:
http://localhost:8888/dev-api/projectcenter/upload/1.jpg
这里的http://localhost:8888是前台vue项目的访问地址。
vue在配置文件中指定了springboot接口的访问地址,真实springboot访问地址为:
http://localhost:9904/projectcenter/
好了,上面是基础条件,现在文件上传时没有问题的,上传到springboot里面指定的本地文件件upload下面了,可是我要在vue项目里面将他回显到页面上,怎么办呢?
步骤如下:1、让springboot将本地文件夹映射出去:注册一个映射。文件放在哪里都ok,springboot会根据注解找到他的:
@Configuration
public class MyWebMVCConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//定义拦截
String resourceHandler="/temp/**";
//获取本地temp文件夹的路径
File file=new File("\temp");
String location=file.getAbsolutePath();
//匹配到resourceHandler,将URL映射至location,也就是本地文件夹
String oLocation="file:" + location+"\";
registry.addResourceHandler(resourceHandler).addResourceLocations(oLocation);
registry.addResourceHandler("/upload/**").addResourceLocations("file:F:\xiazai\");
}
}
注意,本地目录最后必须是斜杠结尾的,标记为目录,要不然最后会访问不到的。
添加之后,运行项目看看,能看见文件就是OK的:
http://localhost:9904/projectcenter/upload/1.jpg
然后,使用vue的地址来看看:
http://localhost:8888/dev-api/projectcenter/upload/1.jpg
也是OK的。
文中标记的最后一个斜杠一定要注意。我就是在这里卡了好长时间。
如果觉得本文有帮助,给打赏吧。快穷死了。



