SpringBoot部署项目到Linux上传文件路径问题
使用项目相对路径上传到话会上传到linux服务器到/tmp 临时文件目录中,但是问题是还会报异常
Caused by: java.io.FileNotFoundException: /tmp/tomcat.8223985333111777969.80/work/Tomcat/localhost/ROOT/file:/project/myblog-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/img/User/v2-3e1d742d3d2a98cbf122b3414ceb29e7_720w.jpg (No such file or directory)
如上述到异常。
解决办法
使用绝对路径
1、但是我们知道服务器访问时是访问服务器url ,所以我们要用url映射到绝对路径中。
package com.Config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {@Value("${file.staticAccessPath}")private String staticAccessPath;@Value("${file.uploadFolder}")private String uploadFolder;@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/img/**").addResourceLocations("classpath:/static/img/");registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");registry.addResourceHandler("/editor.md-master/**").addResourceLocations("classpath:/static/editor.md-master/");// 配置 服务器上的地址 localhost:8080/Users/zlf/myBlog/upload/ 映射到本地linux/Mac /Users/zlf/myBlog/upload/ (需要在前面加 file:)registry.addResourceHandler(staticAccessPath+"**").addResourceLocations("file:"+uploadFolder);super.addResourceHandlers(registry);}
}
附加上上传文件配置
package com.Config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;import javax.servlet.MultipartConfigElement;@Configuration
public class UploadFileConfig {@Value("${file.uploadFolder}")private String uploadFolder;@Beanpublic MultipartConfigElement multipartConfigElement() {MultipartConfigFactory factory = new MultipartConfigFactory();factory.setLocation(uploadFolder);//文件最大factory.setMaxFileSize(DataSize.parse("5MB"));// 设置总上传数据总大小factory.setMaxRequestSize(DataSize.parse("10MB"));return factory.createMultipartConfig();}
}
application.yaml
file:# 服务器上的地址 localhost:8080/Users/zlf/myBlog/uploadstaticAccessPath: /Users/zlf/myBlog/upload/# 本地路径 /Users/zlf/myBlog/uploaduploadFolder: /Users/zlf/myBlog/upload/
这样我们存储图片文件时就存储在linux的绝对路径就行,访问服务器时服务器会自动映射。