SpringBoot 静态资源访问
场景:项目B是后台管理系统,编辑时某条数据时可以给它添加附件资源,保存在d://projects/file/
路径下,项目A是系统前台,主要是展示相关数据,并实现业务。
文件上传:
import com.popsmart.jinganbackend.commen.APIResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@Value("${common.url}")
private String commonUrl;
@Value("${app.folder}")
private String appFilePath;
@Value("${project.annex.path}")
private String annexFilePath;
@PostMapping(value = "/api/uploadAnnex", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public APIResult<List<String>> uploadAnnex(@RequestPart("files") MultipartFile[] files) throws IOException {
List<String> pathNames = new ArrayList<>();
for(MultipartFile file : files){
// 文件夹路径
String fileRealPath = appFilePath + annexFilePath;
// 日期格式化
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String fileNameFormat = "";
// 路径
String iconPath;
// 获取文件名
String fileName = file.getOriginalFilename();
double fileSize = (double) file.getSize() / 1048576;
logger.info("上传"+fileName);
if(fileName != null){
// 重命名, 加上时间
String oriName = file.getOriginalFilename();
assert oriName != null;
int index = oriName.lastIndexOf(".");
fileNameFormat = oriName.substring(0,index) + "_" + df.format(new Date()) + oriName.substring(index);
}
// 拼接路径
iconPath = commonUrl + annexFilePath + fileNameFormat;
pathNames.add(iconPath);
File filePath = new File(fileRealPath, fileNameFormat);
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
file.transferTo(new File(fileRealPath + fileNameFormat));
}
return APIResult.newSuccessResult(pathNames);
}
}
问题1:在项目B中上传资源,显示上传成功,并且文件已经成功保存在对应路径下,但是点击文件链接,404无法访问
解决:
##不知道为什么配置了以下两个属性还是访问不到,所以选择了下面addResourceHandlers()的方式
spring:
##只有静态资源的访问路径为/static/**时,才会处理请求。
##比如访问http://192.168.0.40:8082/static/annex/1_20230216113045.png,
##处理方式是据模式匹配后的文件名查找本地文件
mvc:
static-path-pattern: /static/**
##指定查找的本地文件的位置。
resource:
static-locations: file:${app.folder},classpath:/static/
app:
folder: d://projects/file/
project:
annex:
path: annex/
common:
url: /static/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Value("${app.folder}")
private String FILEPATH;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor())
.excludePathPatterns("swagger-ui.html")
.excludePathPatterns("/swagger-ui/**")
.excludePathPatterns("/swagger-resources/**")
.excludePathPatterns("/v2/api-docs/**")
.excludePathPatterns("/v2/api-docs-ext/**")
.excludePathPatterns("/swagger-resources")
.excludePathPatterns("/error")
.excludePathPatterns("/swagger-ui.html")
.excludePathPatterns("/static/**")
.addPathPatterns("/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 静态资源
// 所有/static开头的请求都是请求静态资源的,记得在上面的拦截器放行
// resourceLocation指明资源存放的位置
registry.addResourceHandler("/static/**")
.addResourceLocations("file:"+FILEPATH);
}
@Bean
public LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}
}
问题2:前台访问项目B上传的文件
解决:只需要把项目A的资源路径也配置为:
spring:
mvc:
static-path-pattern: /static/**
resource:
static-locations: file:${app.folder},classpath:/static/
app:
folder: d://projects/file/
project:
annex:
path: annex/
common:
url: /static/