方法一:使用addResourceHandlers()
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Value("${file.location}")
String filelocation;
@Value("${file.path}")
String filepath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/**
* 访问路径是addResourceHandler()中的路径,映射到访问本地的addResourceLocations()中
*/
registry.addResourceHandler(filepath + "**").addResourceLocations("file:///" + filelocation);
}
}
yml配置
本地的
file:
location: D:/heroesupload/
path: /upload/
线上的
file:
location: /heroesupload/
path: /upload/
上传的后台代码
保存的图片的 路径是 /upload/xxx.png,这样自己方便
其实开始本想只想保存 xxx.png
ps: 控制台就只放部分代码了
@Value("${file.location}")
private String filelocation;
String tempFileName = fileUtil.fileUpload(file, filelocation);
##########################################
@Configuration
public class FileUtil {
@Value("${file.path}")
String filepath;;
/**
* @Author lanren312
* @Description: 单个文件上传
* @param file 文件对象
* @param path 文件存储的路径
* @date 2022/2/6 22:31
*/
public String fileUpload(multipartfile file, String path) throws IOException {
String name = file.getoriginalFilename();
String suffixName = name.substring(name.lastIndexOf("."));
String fileName = UUIDUtil.uuid() + suffixName;
File tempFile = new File(path, fileName);
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdir();
}
if (tempFile.exists()) {
tempFile.delete();
}
tempFile.createNewFile();
file.transferTo(tempFile);
return filepath + tempFile.getName();
}
}
在这里说明下,yml中的配置后都以 ‘/’ 结尾方便,如果不要,有些地方就要 File.separator,比如上面的代码就要这样写
return filepath + File.separator + tempFile.getName();
F12看看查询出来的staffIcon,再去看看addResourceHandlers()里面的配置,就应该明白了吧,图片显示成功。
本地可以,放到云服务器测试也是ok的。
方法二:使用tomcat
1、将本地的tomcat添加到服务并启动
不熟的可以看看我之前写的 windows创建及删除redis、mysql服务_lanren312的博客-CSDN博客_删除redis服务
或者本地临时启动应该也是可以的。
2、配置yml
在tomcat安装目录中新建文件夹 heroesupload
D:\Program Files\apache-tomcat-8.5.56\webapps\heroesupload
本地的
file:
location: D:\Program Files\apache-tomcat-8.5.56\webapps\heroesupload\
path: http://机器ip:8080/heroesupload/
线上的
file:
location: /heroesupload/
path: /upload/
这样配置保存的图片的路径就可以写成 /xxx.png,更简洁
如果使用tomcat配置,千万千万千万要启动tomcat,重要的事说三遍!!!
原文地址:https://www.jb51.cc/wenti/3279755.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。