一、环境说明
前端 vue + 后端 springboot + 文件服务器nginx
项目:https端口8086、http端口8084
文件服务器:http端口35105
注:前后端未分离 ,都在Tomcat容器中
二、问题说明
1.跨域
项目端口为8086或8084,而文件服务器端口为35105,因此直接通过前端发送请求时存在跨域问题。
2.https时不能使用http获取pdf
当使用https协议打开服务端时,因文件服务器对应URL为http协议,浏览器会出于安全考虑对请求进行自动拦截。
3.文件服务器证书为自定义证书,不能通过浏览器的SSL认证。
三、解决方法
方式一:后端接口调用
说明:前端通过调用后端接口获取文件服务器中对应文件的流,从而在前端展示。
前端部分代码示例:
// 预览pdf文件
handlePreviewPdfFile () {
const newFormData = new FormData()
newFormData.append('url', this.url)
apiAPI.previewPdfFile(newFormData).then(res => {
this.pdfUrl = this.getObjectURL(res.data)
})
},
// 将返回的流数据转换为url
getObjectURL (file) {
let url = null
if (window.createObjectURL !== undefined) {
// basic
url = window.createObjectURL(file)
} else if (window.webkitURL !== undefined) {
// webkit or chrome
try {
url = window.webkitURL.createObjectURL(file)
} catch (error) {
console.log(error)
}
} else if (window.URL !== undefined) {
// mozilla(firefox)
try {
url = window.URL.createObjectURL(file)
} catch (error) {
console.log(error)
}
}
return url
}
后端部分代码示例:
public void previewPdfFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
String url = request.getParameter("url");
if (StringUtils.isBlank(url)) {
log.error("请求参数url为空");
return;
}
FileDownLoadConfig fileDownLoadConfig = new FileDownLoadConfig