Vue は、ファイルをダウンロードするためのバイト ストリームを返すバックエンド インターフェイスを実装します。

1. URL経由でダウンロード

window.location.href = ファイルパス経由でダウンロード

window.location.href = `${location.origin}/template` // 后端提供的地址

window.open(url, '_blank') 経由

window.open(`${location.origin}/template`)

window.location: 現在のページにジャンプします。つまり、現在のページの位置を変更します。

window.open: リンクを新しいウィンドウで開きます。

2. BLOB コンストラクターと組み合わせたタグの download 属性を通じてダウンロードする

a タグの download 属性は HTML5 標準に新しく追加されたもので、ブラウザのダウンロード操作をトリガーするために使用され、ダウンロード時に使用する新しいファイル名を設定できます。

フロントエンドはハイパーリンクを作成し、バックエンドからファイル ストリームを受け取ります。

axios.get(`/template`, {
        responseType: "blob" //服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream',默认是'json'
    })
    .then(res => 
        if(!res) return
        let fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1].replace(/\"/g, ''))
        const blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' }) // 构造一个blob对象来处理数据,并设置文件类型 excel:application/vnd.ms-excel zip: application/zip
          
        if (window.navigator.msSaveOrOpenBlob) { //兼容IE10
            navigator.msSaveBlob(blob, filename)
        } else {
            const href = URL.createObjectURL(blob) //创建新的URL表示指定的blob对象
            const a = document.createElement('a') //创建a标签
            a.style.display = 'none'
            a.href = href // 指定下载链接
            a.download = filename //指定下载文件名
            document.body.appendChild(a);
            a.click() //触发下载
            URL.revokeObjectURL(a.href) //释放URL对象
            document.body.removeChild(a);
        }
        // 这里也可以不创建a链接,直接window.open(href)也能下载
    })
    .catch(err => {
        console.log(err)
    })

バックグラウンド インターフェイスをリクエストする場合は、リクエスト ヘッダーに {responseType: 'blob'} を追加します。ダウンロード ファイル名を設定するときに、拡張子を直接設定できます。設定されていない場合、ブラウザは自動的に正しいファイル拡張子を検出し、それを追加しますファイル。

3. js-file-download プラグイン経由

import fileDownload from 'js-file-download'
  
axios.get(`/template`, {
        responseType: 'blob' //返回的数据类型
    })
    .then(res => {
        fileDownload(res.data, fileName)
    })

おすすめ

転載: blog.csdn.net/jiangzhihao0515/article/details/129140776