如何判断一个文件链接在浏览器中打开是预览还是下载?

956 阅读1分钟

FAQ

1、打开链接如何直接预览 PDF ?

链接响应头属性为 Content-type: application/pdf;Content-Disposition: inline

2、打开链接如何直接下载 PDF ?

方式一:

链接返回文件流,即响应头属性为 Content-type: application/octet-stream

方式二:

链接响应头属性为 Content-type: application/pdf ; Content-Disposition: attachment

3、如何查看链接的响应头?

用 Postman 请求,查看返回的 headers 即可

4、如何设置响应头?

拿着板砖 🧱 找后端就行

具体描述

浏览器打开文件链接是预览还是下载取决于链接响应头的两个字段:

Content-Disposition 表示链接内容是下载还是直接打开

属性描述
inline直接预览(默认)
attachment直接下载
attachment; filename=filename.jpg下载并给下载文件命名

Content-type 指链接资源的类型

属性描述
text/htmlHTML
text/plain纯文本
text/xmlXML
image/gifgif 图片
image/jpegjpg 图片
image/pngpng 图片
application/xmlXML 数据格式
application/jsonpdf
application/mswordWord 文档
application/octet-stream二进制流数据
application/x-www-form-urlencoded表单发送默认格式
audio/mp3mp3 文件
video/mpeg4mp4 文件

下载还是预览可以直接根据以上两个响应头属性结合即可

PS:当 Content-type: application/octet-stream 为二进制流的时,不管 Content-Disposition 的属性为何值,都会直接下载