使用SpringBoot设置虚拟路径映射绝对路径
SpringBoot 设置虚拟路径映射绝对路径
上传图片到本地路径,得到的是一个绝对路径例如:D:\picpath\O48681516429132485.png
但是前台需要的数据是这样的 :http://localhost:8082/image/O48681516429132485.png
那么就要设置虚拟路径 /image/ = D:\picpath\ 了,
下面我们就来代码实现下
作为一个负责任的程序员,我把包也给你们复制过来了。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 图片绝对地址与虚拟地址映射
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//文件磁盘图片url 映射
//配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
registry.addResourceHandler("/image/**").addResourceLocations("D:\\picpath\\");
}
}
是不是很简单呢?
springboot打war包图片的虚拟路径映射
这里我将自己学习的项目为例子作个简单的记录:
在html图片的路径如图

这里是头像路径的映射
然后要映射到阿里云Linux服务器上路径

注意,这两个路径是不同的,只是同名而已,HTML那里的路径可以随便修改,到最后映射到这个路径就可以,当然映射到别的路径也可以
映射方法
找到tomcat下的config下的server.xml文件

在Host节点加上下面的

前面是path是虚拟路径,对应的是HTML那里的代码,后面是真实路径,对应Linux上面真实路径
这里顺便放上后台接收上传头像的代码
@ResponseBody
@RequestMapping("uploadImage")
public DataGridView uploadImage(MultipartFile file, HttpSession session) throws Exception {
DataGridView dataGridView = null;
if (!file.isEmpty()){
String filename = file.getOriginalFilename(); //abc.jpg
String suffix = filename.substring(filename.lastIndexOf(".")); //后缀 如abc.jpg,就是jpg
String newFileName = DateUtil.getCurrentDateStr() + suffix; //新文件名
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(userImageFilePath+newFileName));
Map<String,Object> map= new HashMap<>();
map.put("src","/project/userImages/"+newFileName);
map.put("title",newFileName);
dataGridView = new DataGridView(0, "上传成功", map);
User currentUser = (User) session.getAttribute("currentUser");
currentUser.setImageName(newFileName);
userService.save(currentUser);
session.setAttribute("currentUser",currentUser);
System.out.println("执行完了");
}
return dataGridView;
}
顺便说下war包放到阿里云服务器上路径映射(域名或者IP直接访问项目根路径):
<Context path="/" docBase="/home/tomcat/apache-tomcat-8.5.45/webapps/code007" debug="0" reloadable="true"/>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
关于Springboot数据库配置文件明文密码加密解密的问题
这篇文章主要介绍了Springboot数据库配置文件明文密码加密解密的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-03-03
为什么Spring官方推荐的@Transational还能导致生产事故
在Spring中进行事务管理非常简单,只需要在方法上加上注解@Transactional,那么为什么Spring官方推荐的@Transational还能导致生产事故,本文就详细的介绍一下2021-11-11
聊聊Springboot2.x的session和cookie有效期
这篇文章主要介绍了Springboot2.x的session和cookie有效期,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-09-09


最新评论