SpringBoot配置图片访问的虚拟路径

网友投稿 871 2022-10-29

SpringBoot配置图片访问的虚拟路径

记录一次SpringBoot配置虚拟路径访问图片的笔记最近编写的项目都是需要将图片进行访问的,而我的是有spring+springMVC+Mybatis框架实现的项目,并且在使用ssm框架的时候已经是用到了图片访问的虚拟路径来进行访问的,ssm配置虚拟路径实在Tomcat上配置的图片访问,而SpringBoot是内置Tomcat的那应该怎么配置呢具体看下图,先配置图片上传路径

这个是jsp页面的代码段

上传图片

js代码段

upload.render({ //这里是上传一张图片

elem: "#SingleUpload",

url: ctx + "/book/SingleUpload",

done: function (res, index, upload) {

//假设code=0代表上传成功

if (res.code == 0) {

layer.msg("简介图片加载成功!", {icon: 1});

$("#simpleImg").attr("src", res.image);

$("#SingleUpload").addClass("layui-btn-disabled");

$("#SingleUpload").off("click");

}

}

});

接下来是Controller里面的具体配置

private String simplePath = "D:/uploadLibrary/";

// 详细图片地址

private StringBuilder detailsPath = new StringBuilder();

@RequestMapping("/SingleUpload")

@ResponseBody

public Map SingleUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req,

HttpSession session) {

Map map = new HashMap();

try {

String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

String filename = UUID.randomUUID() + suffixName;

File filePath = new File(dirPath);

if (!filePath.exists()) {

filePath.mkdirs();

}

//创建虚拟路径存储

simplePath = req.getServletContext().getContextPath() + "/file/" + filename;

// simplePath = filename;

map.put("image", simplePath);

file.transferTo(new File(dirPath + filename));

map.put("code", 0);

map.put("msg", "上传成功");

} catch (Exception e) {

map.put("code", 1);

map.put("msg", "上传失败");

e.printStackTrace();

}

return map;

}

数据库存储的图片路径

一切都设置好了过后这时就需要对SpringBoot配置虚拟路径来对图片进行访问了新建config 控制类在里面新建类方法WebMvcConfig来对图片进行虚拟路径的配置具体代码

package com.book.libratyman.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.shttp://ervlet.config.annotation.WebMvcConfigurer;

@Configuration

public class WebMvcConfig implements WebMvcConfigurer {

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/file/**").addResourceLocations("file:D:/uploadLibrary/");

}

}

addResourceHandler("/file/**")是我在项目中访问图片的路径也就是数据里面的图片存储路径,而addResourceLocations(“file:D:/uploadLibrary/”)则是我上传图片的真实路径我上传图片的真实路径是 **D:/uploadLibrary/**配置以后运行项目便可以访问项目图片了。

图片显示出来就表示已经配置成功了哦!!!!!

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spark pipe PHP 实例
下一篇:数组----第一题
相关文章

 发表评论

暂时没有评论,来抢沙发吧~