最近在做的一个项目中有一个比较奇葩的需求:
要在springboot
中,上传本地的图片进行展示
我的第一反应是,直接在数据库字段加一个存储本地路径的字段,然后用thymeleaf
的th:src
渲染到前端就好了嘛!
理想很丰满,但现实却很骨感~
前端报了这样的错误Not allowed to load local resource
于是我想到了可以使用IO将图片先上传到static/images
目录下,这样就不会出现禁止访问本地路径的问题了
但是这样实现,问题又来了:上传后的图片必须重启springboot
,才能进行展示,否则无法加载
这个应该是因为springboot
在初始化时加载静态资源,运行时导入的资源只能在再次初始化时加载
于是,我苦思冥想,查阅了多方资料,终于使用本地虚拟路径
的方式,解决了这个问题
正片开始:
- 首先配置一个配置类
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()}}">
这样就成功实现需求啦