前端下载后端返回的文件流,取请求头content-disposi

2023-05-04  本文已影响0人  码农私房菜

解决办法

{
"access-control-allow-credentials": "true",
"access-control-allow-headers": "Origin, X-Requested-With,Access-Control-Allow-Headers, Authorization, Content-Type, Accept, Connection, User-Agent, Cookie",
"access-control-allow-methods": "*",
"access-control-allow-origin": "http://localhost.com:8080",
"access-control-max-age": "3600",
"cache-control": "max-age=0",
"connection": "close",
"content-disposition": "attachment; filename=%E5%93%81%E7%89%8C%E7%AE%A1%E7%90%86.xlsx",
"content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
"date": "Fri, 05 May 2023 11:16:25 GMT",
"expires": "Fri, 05 May 2023 11:16:25 GMT",
"server": "openresty",
"transfer-encoding": "chunked",
"x-powered-by": "Express"
}

    let blob = new Blob([res?.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' }) // 处理文档流
    const elink = document.createElement('a') // 创建a标签
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob) // 创建blob地址
    document.body.appendChild(elink) // 将a标签添加到body中
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL对象
    document.body.removeChild(elink) // 从body中移除a标签
在开发环境http协议能拿到headers参数,但是发完线上https后拿不到想要的数据,可明明在控制台Network里明明能看到,但是在响应拦截器里用js headers["content-disposition"]来获取,但是打印 header对象里并没有content-disposition,无法获取,这是什么原因?

这里的暴露给外部,意思是让客户端可以访问得到,既可以在Network里看到,也可以在代码里获取到他们的值。

上面问题提到的content-disposition不在其中,所以即使服务器在协议回包里加了该字段,但因没“暴露”给外部,客户端就“看得到,拿不到”。

而响应首部 Access-Control-Expose-Headers 就是控制“暴露”的开关,它列出了哪些首部可以作为响应的一部分暴露给外部。所以如果想要让客户端可以访问到其他的首部信息,服务器不仅要在heade里加入该首部,还要将它们在 Access-Control-Expose-Headers 里面列出来。

解决办法

需要后端同学设置响应头:

response.setHeader("Access-Control-Expose-Headers", "Content-Disposition")
response.setHeader("Content-Disposition", ...)
设置成功后,浏览器Network可以看到:

{
"access-control-allow-credentials": "true",
"access-control-allow-headers": "Origin, X-Requested-With,Access-Control-Allow-Headers, Authorization, Content-Type, Accept, Connection, User-Agent, Cookie",
"access-control-allow-methods": "*",
"access-control-allow-origin": "http://localhost.com:8080",
"access-control-max-age": "3600",
"access-Control-Expose-Headers":"Content-Disposition",
"cache-control": "max-age=0",
"connection": "close",
"content-disposition": "attachment; filename=%E5%93%81%E7%89%8C%E7%AE%A1%E7%90%86.xlsx",
"content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
"date": "Fri, 05 May 2023 11:16:25 GMT",
"expires": "Fri, 05 May 2023 11:16:25 GMT",
"server": "openresty",
"transfer-encoding": "chunked",
"x-powered-by": "Express"
}
上一篇 下一篇

猜你喜欢

热点阅读