vue プロジェクトのフロントエンドは PDF ファイルのダウンロードを実装します

インターフェイスから PDF の URL を取得し、フォアグラウンドでダウンロード機能を実現します

アイデア: get リクエストを使用してバイナリ ストリームを取得し、それを Blob に変換し、window.URL.createObjectURL() を通じて DOMString を作成し、それを a タグの href に割り当てます。具体的な実装は次のとおりです。ステップ 1: BLOB にはバイナリ ストリームが必要なため
Get は PDF パスをリクエストします。

/*
    url: "http://124.127.246.224:9000/images/2022/10/17/c24f8fd7d53.pdf"
    options: {title:"",fileType:"application/pdf"}
    ele: a标签
*/
let getFile = (url, options, ele) => {
    
    
    axios.get(url,{
    
     responseType: 'blob' }).then(res => download(res, options, ele))
}

ステップ 2: 返されたデータを BLOB に変換する

let download = (res, options, ele) => {
    
    
    let blob = new Blob([res.data], {
    
     type: options.fileType ? options.fileType : "application/octet-binary" });
    let href = window.URL.createObjectURL(blob);
    downloadBlob(href, options, ele);
}

ステップ 3: ダウンロードを実行する
ここでの落とし穴: ele.click() を追加しない場合、ファイルをダウンロードするにはもう一度クリックする必要があります。クリックセルフコールを追加すると、ダウンロードが 2 回行われるため、フラグを使用して記録します

let flag = 1;
let downloadBlob = (blobUrl, options, ele) => {
    
    
    ele.href = blobUrl;
    ele.download = options.title;
    flag++;
    if ((flag % 2) == 0) {
    
    
        ele.click();
        window.URL.revokeObjectURL(blobUrl);//释放
    }
}

ステップ 4: vue ファイルを呼び出す

 <el-button type="primary"  @click="download(ele, index)">下载
     <a :id="'d' + index"></a>
 </el-button>

import {
    
    getFile} from "@/utils/download"

download(data, index) {
    
    
  let arr = data.url.split(".");
  let options = {
    
    
    title: data.title,
    fileType: "application/"+arr[arr.length-1]
  };
  let link = document.getElementById("d" + index);
  getFile(data.url,options,link)
},

js ファイルの完全な内容は次のとおりです。

//download.js
import axios from "axios"  //需要单独引入,因为当前.js文件不会被vue管理
axios.defaults.headers['Cache-Control'] = 'no-cache'
/*
    url: "http://124.127.246.224:9000/images/2022/10/17/c24f8fd7d53.pdf"
    options: {title:"",fileType:"application/pdf"}
    ele: a标签
*/
let getFile = (url, options, ele) => {
    
    
    axios.get(url, {
    
     responseType: 'blob' }).then(res => download(res, options, ele))
}

let download = (res, options, ele) => {
    
    
    let blob = new Blob([res.data], {
    
     type: options.fileType ? options.fileType : "application/octet-binary" });
    let href = window.URL.createObjectURL(blob);
    downloadBlob(href, options, ele);
}

let flag = 1;
let downloadBlob = (blobUrl, options, ele) => {
    
    
    ele.href = blobUrl;
    ele.download = options.title;
    flag++;
    if ((flag % 2) == 0) {
    
    
        ele.click();
        window.URL.revokeObjectURL(blobUrl);
    }
}

export {
    
    
    getFile,
    download,
    downloadBlob
}

もっと良い書き方があれば修正大歓迎です、よろしくお願いします〜

おすすめ

転載: blog.csdn.net/qq_44415875/article/details/127756706