在浏览器中下载文件的需求
- 通过 window 对象的 open 方法进行操作,将文件 url 直接在浏览器中打开
// 微信公众号可支持下载pdf、docx文件
window.open(URL)
- 通过 a 标签,设置 href 为 url 值,点击 a 标签即可完成下载。
<a href="URL">下载</a>
上面两种文件下载方式都会存在一个问题,就是 PC端pdf 文件会直接在浏览器中打开而不是直接下载
解决方案:
- 这种需求的解决方式就是将PDF文件的
MIME type改为application/octet-stream并加入Content-Disposition:attachment header。 - (原本的 pdf 文件
MIME type默认为application/pdf,浏览器识别到这个 type 之后会自动在浏览器打开) 所以说我们在这里修改 type 即可。
前端实现
// 传入pdf文件的远程地址(文件在服务器上存放的地址url)即可实现下载,其中a.download可设置下载后文件名称
fetch(url, {
method: 'get',
responseType: 'arraybuffer',
}).then(res => {
if (res.status !== 200) {
return res.json()
}
return res.arrayBuffer()
}).then(blobRes => {
// 生成 Blob 对象,设置 type 等信息
const e = new Blob([blobRes], {
type: 'application/octet-stream',
'Content-Disposition':'attachment'
})
// 将 Blob 对象转为 url
const link = window.URL.createObjectURL(e)
let a = document.createElement('a');
a.href = link;
a.download = '文件名称.pdf';
a.click();
}).catch(err => {
console.error(err)
})