在测试本地服务上传文件时发现 为什么通过nacos 配置参数后 上传文件后返回的url
http://127.0.0.1:9300/statics/2022/03/04/verison_1646127256070_20220304141419A001.xlsx
就可以直接访问到本地文件 后来发现 是如下的代码在生效
package com.ruoyi.file.config;
import java.io.File;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 通用映射配置
*
* @author ruoyi
*/
@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{
/**
* 上传文件存储在本地的根路径
*/
@Value("${file.path}")
private String localFilePath;
/**
* 资源映射路径 前缀
*/
@Value("${file.prefix}")
public String localFilePrefix;
/* 匹配了 请求http://127.0.0.1:9300/statics/2022/03/04/xxx.xlsx 本地文件路径通过localFilePath 参数 配置到 配置到真正的本地文件 */
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
/** 本地文件上传路径 */
registry.addResourceHandler(localFilePrefix + "/**")
.addResourceLocations("file:" + localFilePath + File.separator);
}
/**
* 开启跨域 以允许匹配localFilePrefix的请求
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路由
registry.addMapping(localFilePrefix + "/**")
// 设置允许跨域请求的域名
.allowedOrigins("*")
// 设置允许的方法
.allowedMethods("GET");
}
}

这篇博客介绍了如何在Spring MVC中配置资源处理器以实现本地文件的访问,并通过WebMvcConfigurer接口添加资源映射和跨域设置。通过`addResourceHandlers`方法,将上传的文件路径映射到特定URL前缀,使得可以直接通过该URL访问本地文件。同时,使用`addCorsMappings`方法设置跨域策略,允许所有来源的GET请求。这样,本地文件上传后,可以通过配置的URL直接访问,并且支持跨域请求。

被折叠的 条评论
为什么被折叠?



