如何使 pdf 文件在浏览器里面直接下载而不是打开

前言

在做需求过程中我们大概率会遇到在浏览器中下载文件的需求,如果仅仅是这个要求的话很简单,但是平常下载方式都会存在一个问题,就是 pdf 文件会直接在浏览器中打开而不是直接下载。

解决方案

这种需求的解决方式就是将PDF文件的 MIME type 改为 application/octet-stream 并加入 Content-Disposition:attachment header,原本的 pdf 文件 MIME type 为 application/pdf,浏览器识别到这个 type 之后会自动在浏览器打开,所以说我们在这里修改 type 即可。(前后台都可以,我们本次采用前台)

代码如下:

//下载文件的链接
var url="xxxxx";
  fetch(url, {
    method: 'get',
    responseType: 'arraybuffer',
  })
    .then(function (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)
      handleFileDownload(link, filename)
    }).catch(err => {
      console.error(err)
    })
原文地址:https://www.cnblogs.com/alives/p/15169066.html