欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于Springboot2.3访问本地路径下静态资源的方法(解决报错:Not allowed to load local resource)

程序员文章站 2022-04-05 14:58:47
最近在做的一个项目中有一个比较奇葩的需求:要在springboot中,上传本地的图片进行展示我的第一反应是,直接在数据库字段加一个存储本地路径的字段,然后用thymeleaf的th:src渲染到前端就...

最近在做的一个项目中有一个比较奇葩的需求:

要在springboot中,上传本地的图片进行展示

我的第一反应是,直接在数据库字段加一个存储本地路径的字段,然后用thymeleaf的th:src渲染到前端就好了嘛!

理想很丰满,但现实却很骨感~

前端报了这样的错误not allowed to load local resource

基于Springboot2.3访问本地路径下静态资源的方法(解决报错:Not allowed to load local resource)

于是我想到了可以使用io将图片先上传到static/images目录下,这样就不会出现禁止访问本地路径的问题了

但是这样实现,问题又来了:上传后的图片必须重启springboot,才能进行展示,否则无法加载

这个应该是因为springboot在初始化时加载静态资源,运行时导入的资源只能在再次初始化时加载

于是,我苦思冥想,查阅了多方资料,终于使用本地虚拟路径的方式,解决了这个问题

正片开始:

1.首先配置一个配置类

import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.resourcehandlerregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;

@configuration
public class myconfigurer implements webmvcconfigurer {
  @override
  public void addresourcehandlers(resourcehandlerregistry registry) {
    registry.addresourcehandler("/image/**").addresourcelocations("file:e:/vote_images/");
  }
}

addresourcehandler是指你设置的虚拟路径,前端展示页面时填入这个路径来进行访问

addresourcelocations是指实际的本地路径,你需要代理给虚拟路径来访问的路径

2. io实现文件上传

//如果文件夹不存在,创建文件夹
file file=new file("e:\\vote_images");
if(!file.exists()){
  file.mkdir();
}
//文件的上传
try (inputstream input = new fileinputstream(new file(judge));
   outputstream output = new fileoutputstream("e:\\vote_images\\" + num + ".jpg")
   ) {
  byte[] buf = new byte[1024];
  int bytesread;
  while ((bytesread = input.read(buf)) != -1) {
    output.write(buf, 0, bytesread);
  }
} catch (ioexception e) {
  e.printstacktrace();
}
//设置路径字段
o.setpath("\\image\\" + (num++) + ".jpg");
//增加数据
optionsservice.insert(o);

3.前端渲染页面

<img height="150px" width="225px" th:src="@{${opt.getpath()}}">

这样就成功实现需求啦

到此这篇关于基于springboot2.3访问本地路径下静态资源的方法的文章就介绍到这了,更多相关springboot2.3访问本地静态资源内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!