JS 通過后台接口返回的URL地址下載文件並保存到本地(已在項目中使用,保存音視頻文件)


今天做antdV表格勾選下載操作時,因為粗心大意碰到了下載問題,特此記錄~

一、單個文件下載邏輯代碼如下:

const exportFile = (data, fileName, _this)=>{
 // 地址不存在時,禁止操作
  if(!data)return;
// 下載文件並保存到本地 const callback
= (data)=>{
   // 創建a標簽,使用 html5 download 屬性下載, const link
= document.createElement('a');
   // 創建url對象 const objectUrl
= window.URL.createObjectURL(new Blob([data])); link.style.display='none'; link.href=objectUrl;
   // 自定義文件名稱,
fileName
   link.download = fileName;
   document.body.appendChild(link);
   link.click();
   // 適當釋放url
window.URL.revokeObjectURL(objectUrl);
 };
// 把接口返回的url地址轉換為 blob const xhr
= new XMLHttpRequest(); xhr.open('get', data, true); xhr.responseType = 'blob'; xhr.onload = ()=> {
   // 返回文件流,進行下載處理 callback(xhr.response); }; xhr.send(); // 不要忘記發送 };

//
ie和瀏覽器兼容模式會有問題,可以用下面代碼調試。
 try{
    exportFile(); // 調用方式
  }catch(err){
    // 兼容模式下,IE
    const exportBlob = new Blob([data]);
    if (navigator.userAgent.indexOf('Trident') > -1) {
      window.navigator.msSaveBlob(data, fileName);
    } else {
      exportFile(); // 調用方式
    }
  };
  

調用方式:

exportFile('https://reading.oss.iyougu.com/uploads/mp/opus/1c5a8b6a391742cf93595d0a506b2d43.mp3', '測試.mp3');
exportFile('https://reading.oss.iyougu.com/uploads/mp/opus/2595f553407e471085de7f508afe5cb9.mp4', '測試.mp4');

  *表格數據有音頻、視頻文件,所以邏輯上區分了文件后綴名!

二、批量下載,壓縮打包成zip:

  項目框架用的vue,已安裝 axios,先安裝依賴 jszip , file-saver;

    npm install jszip
    npm install file-saver

  

  主要業務代碼如下:

  

    function filesToRar(arr, filename){
      const _this=this;
      const zip = new JSZip(); // 創建實例
      const cache = {}; // 記錄壓縮文件,不做實際用處
      const promiseArr = []; // 異步存儲下載的二進制數據
      _this.$message.loading({ content: '正在加載壓縮文件', key: 'filesRAR'}); // 結合antdv 組件提示
      const getFile = url => {
        url = url.replace('http://','https://'); // 根據域名有必要進行替換
        return new Promise((resolve, reject) => {
          axios({
            method:'get',
            url,
            responseType: 'arraybuffer'
          }).then(data => {
            resolve(data.data);
          }).catch(error => {
            reject(error.toString()); // 異常信息,暫不接收
          });
        });
      };
      for(const item of arr){
        const promise = getFile(item.yunUrl).then(res =>{
          const name = item.resName;
          const type = item.opusType === '視頻'?'mp4':'mp3'; // 區分音視頻鏈接,並重命名
          zip.file(`${name}.${type}`, res, { binary: true}); // 添加文件,res可以是File文件也可以是Blob二進制數據。
      // 或者zip.folder添加成文件夾
          cache[name]=res;
        });
        promiseArr.push(promise); // 追加數據
      }
      Promise.all(promiseArr).then(() => {
     // 生成zip文件 zip.generateAsync({ type:
'blob'}).then(content => { _this.$message.loading({ content: '正在壓縮', key: 'filesRAR'}); FileSaver.saveAs(content, filename); // 生成二進制流,可以上傳也可以存儲。此處是瀏覽器打包並下載。 _this.$message.success({ content: '壓縮完成', key: 'filesRAR'}); _this.isLoading = false; }); }).catch(err =>{ console.log(err); _this.isLoading = false; _this.$message.error('文件壓縮失敗'); }); }

調用方式:   filesToRar(arr, '文件.zip')  

注意:下載的文件是音視頻文件,等待時間稍長,大家有什么好的解決辦法嗎?

 

 完成!o(* ̄▽ ̄*)ブ

如果您覺得有用的話給個推薦吧😊

有問題在評論區多多交流嗷~~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM