需求要求根据查询数据生成PDF直接展示在iframe中,生成的文件保存在磁盘固定位置,并没有放在静态资源文件夹,iframe又需要访问同源,所以需要拦截请求访问本地资源实现;
springboot项目中创建xxxxconfig类实现WebMvcConfigurer接口
重写addResourceHandlers方法
@Value("${filePath.path}")
private String filePath;
@Value("${filePath.opeReportPath}")
private String opeReportPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 运维报告访问PDF,指向本地磁盘
registry.addResourceHandler(opeReportPath).addResourceLocations("file:" + ("/".equals(filePath.substring(filePath.lastIndexOf("/"))) ? filePath : filePath + "/"));
}
filePath为本地文件存储路径,注意addResourceLocations的路径一定要以"/"结尾
opeReportPath为需拦截的路径:"/opeReport/**"
此时,当生成完PDF文件后,直接将文件名称返回给前端,iframe的src指定为ip:端口/opeReport/文件名即可,此时即可访问到本地磁盘对应文件展示在iframe中