方法一:使用addResourceHandlers()
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Value("${file.path}")
String filepath;
@Value("${file.prefix}")
String fileprefix;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/**
* 访问路径是addResourceHandler()中的路径,映射到访问本地的addResourceLocations()中
*/
registry.addResourceHandler(fileprefix + "**").addResourceLocations("file:///" + filepath);
}
}
yml配置
本地的
file:
path: D:/heroesupload/
prefix: /upload/
线上的
file:
path: /heroesupload/
prefix: /upload/
上传的后台代码
保存的图片的 路径是 /upload/xxx.png,这样自己方便
其实开始本想只想保存 xxx.png
ps: 控制台就只放部分代码了
@Value("${file.path}")
private String filepath;
String tempFileName = fileUtil.fileUpload(file, filepath);
##########################################
@Configuration
public class FileUtil {
@Value("${file.prefix}")
String fileprefix;
/**
* @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 fileprefix + tempFile.getName(); // 这里多了一个 fileprefix, 也就是 /uplaod
}
}
在这里说明下,yml中的配置后都以 ‘/’ 结尾方便,如果不要,有些地方就要 File.separator,比如上面的代码就要这样写
return fileprefix + 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:
path: D:\Program Files\apache-tomcat-8.5.56\webapps\heroesupload\
prefix: http://机器ip:8080/heroesupload/
线上的
file:
path: /data/vue/heroesupload/
prefix: http://服务器ip/heroesupload/ #使用了nginx配置/data/vue
这样配置保存的图片的路径就可以写成 /xxx.png,更简洁
说明下,本地的 filepath是下载路径,fileprefix是查看路径,这个你应该懂吧
线上的也是一样,可以配合nginx用,tomcat也行
如果使用tomcat配置,千万千万千万要启动tomcat,重要的事说三遍!!!