问题描述
127.0.0.1/:1 Access to XMLHttpRequest at 'http://127.0.0.1:9010/webSDK/assets/1-feature-example_default-setup.pdf' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
代理到静态资源配置类
pathPattern:为拦截的地址
如最终访问结果地址为:http://127.0.0.1:9010/files/1701243349887.pdf
import com.jeesite.modules.foxitpdf.utils.Stream2File;
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.WebMvcConfigurer;
/**
* Date:2023/11/29
* Author:zhushihua
* Description:
* 解决打开跨域pdf问题
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
//拦截的url,虚拟路径
@Value("${pathPattern}")
String pathPattern;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//将匹配上/files/**虚拟路径的url映射到文件上传到服务器的目录,获取静态资源
registry.addResourceHandler("/" + pathPattern + "/**").addResourceLocations("file:" + Stream2File.filePath);
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
读取http开头的url路径文件,并写到自定义目录
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
/**
* Date:2023/11/28
* Author:zhushihua
* Description:
*/
@Slf4j
public class Stream2File {
//自己设置的目录
private static final String fileDir = "fileStorage";
public static String filePath = System.getProperty("user.dir") + File.separator + fileDir + File.separator;
private static final AtomicInteger SUFFIX = new AtomicInteger(0);
public static String inputStream2FileWrite(String fileURL){
String fileName = ""; // 最终前端访问的路径
try {
URL url = new URL(fileURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
InputStream intputStream = conn.getInputStream();
//首次需生成目录
File folder = new File(filePath);
if (!folder.exists()) {
folder.mkdirs();
}
fileName = System.currentTimeMillis() + SUFFIX.getAndIncrement() + ".pdf";
String absolutePath = filePath + fileName;
//写入到固定的目录
FileOutputStream fos = new FileOutputStream(absolutePath, true);
byte[] b = new byte[1024];
int length;
while ((length = intputStream.read(b)) > 0) {
fos.write(b, 0, length);
}
// 关闭输入流和输出流
intputStream.close();
fos.close();// 保存数据
}catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
}
yml中配置
# 拦截的url,虚拟路径,解决打开跨域pdf问题 pathPattern: filess