文件下载方式

直接下载

针对一些浏览器无法识别的文件格式。可以直接在地址栏上出入URL即可触发浏览器的下载功能。

同类的还有window.location.hrefwindow.open

  • 地址栏输入文件URL
  • window.location.href = URL
  • window.open(URL)

使用a标签download属性

直接下载仅使用的浏览器无法识别的文件。如果是浏览器支持的文件格式(如:htmljpgpng)等。则不会触发文件下载,而是被浏览器直接触发解析展示。

针对这种情况,我们可以使用a标签的download属性,可以设置文件名。

<a href="/images/download.jpg" download="myFileName">

开发中,我们遇到的还有一部分场景是js直接触发下载,也是相同的做法,我们可以手动写一个a标签。appenbody里边,触发下载之后,将其remove

const download = (filename, link) => {
    let DownloadLink = document.createElement('a'); 
    DownloadLink.style = 'display: none'; // 创建一个隐藏的a标签
    DownloadLink.download = filename;
    DownloadLink.href = link;
    document.body.appendChild(DownloadLink);
    DownloadLink.click(); // 触发a标签的click事件
    document.body.removeChild(DownloadLink);
}

后端兼容处理attachment

有很多场景。有些浏览器可识别的文件格式,我们还是需要直接下载的情况(如:用户直接分享的下载pdftxt;很多浏览器也是支持展示的)。

这种情况下,我们需要声明一下文件的header的 Content-Disposition信息。告诉浏览器,该链接为下载附件链接,并且可以声明文件名(方式二也可以下载该类型文件,不过文件名会以header设置的文件名优先)。同类的方法还有将文件作为outstream返回

Content-Disposition: attachment; filename="filename.xls"

axios下载

在部分场景中,有一些文件,需要用户登录之后根据权限来开放下载(报表等)。此时,我们需要将本地的用户信息传给服务端。常用的方式如:在header增加token。

axios({
    method:'get',
    url: '/download/file.doc'
    // responseType 值可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
    responseType: 'blob',
    headers: {
        Authorization: '123456'
    },
    onDownloadProgress: function (e) {
       // 对原生进度事件的处理
         console.log('进度计算',(e.loaded/e.total*100).toFixed(2)+'%')
    },
}).then(res => {
    const blob = new Blob([res])
    const fileUrl = window.URL.createObjectURL(blob)
    const DownloadLink = document.createElement('a')
    DownloadLink.style = 'display: none'
    DownloadLink.download = 'filename'
    DownloadLink.href = fileUrl
    document.body.appendChild(DownloadLink)
    DownloadLink.click()
    document.body.removeChild(DownloadLink)
    window.URL.revokeObjectURL(fileUrl)
})