亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue實(shí)現(xiàn)各種文件文檔下載及導(dǎo)出示例

 更新時間:2023年06月30日 14:44:57   作者:陶菇?jīng)? 
這篇文章主要介紹了vue實(shí)現(xiàn)各種文件文檔下載及導(dǎo)出示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

1.下載本地的文件

在vue-cli 3.x+中,直接將文件放在public下面

     window.location.href="/file/xxx.doc" rel="external nofollow" 

這種寫法本地不會有問題,但是線上部署出現(xiàn)了問題,顯示文件找不到;所以改為
window.location.href=`${process.env.BASE_URL}file/beian_import.xls`當(dāng)前也可以不用window.location.href來下載,可以使用dom動態(tài)生成a標(biāo)簽來下載;

downExcel(){
      var link = document.createElement("a"); 
      link.setAttribute("download", "");
      link.href = `${process.env.BASE_URL}file/beian_import.xls`;
      link.click();
      link.remove();
    },

在vue-cli 2.x+中將文件放置在static文件夾下面

    window.location.href="http://localhost:8080/static/template.xlsx" rel="external nofollow"  ; 

2.下載后臺返回數(shù)據(jù)成功的json文件

    downJson(data,file_name){
       exportRecordDown(data).then(res=>{
       var data = JSON.stringify(res.data) 
      //encodeURIComponent解決中文亂碼  data:text/csv;charset=utf-8,\uFEFF(加    \uFEFF是實(shí)現(xiàn)bob)
      let uri ='data:text/csv;charset=utf-8,' +encodeURIComponent(data);
      //通過創(chuàng)建a標(biāo)簽實(shí)現(xiàn)
      let link = document.createElement("a");
      link.href = uri;
      //對下載的文件命名
      link.download =  file_name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
   })
},

3.下載csv文件

handleExport(){
        if(!this.tableData || this.tableData.length <=0 ){
            this.$message.error('沒有要導(dǎo)出的數(shù)據(jù)')
            return
  }
        let csvContent = this.headerLabel + '\n\t'
        this.tableData.forEach((item, index) => {
            let dataString = ''
            for(let i = 0; i < this.headerProp.length; i++ ){
            //如果數(shù)據(jù)為null或者undefined, 下載下來的數(shù)據(jù)框中會被直接填寫上null或undefined
            //可根據(jù)個人選擇自行選擇是否需要這行代碼
                if(item[this.headerProp[i]]==null||item[this.headerProp[i]]==undefined){
                    item[this.headerProp[i]] = ''
                }
                dataString += item[this.headerProp[i]] + ','
            }
            csvContent += (index < this.tableData.length ? dataString.replace('/,$/', '\n\t') : dataString.replace('/,$/', '\n\t'))+'\n\t'
  })
  console.log(csvContent)
        //最終csvContent的格式為"col1,col2,col3 \n value1, value2, value3 \n value4, value5, value6"
        //data:text/csv;charset=utf-8,\ufeff, utf-8的編碼格式,保證中文不亂碼
        // this.$refs.link.setAttribute('href', 'data:text/csv;charset=utf-8,\ufeff'+encodeURIComponent(csvContent))
  // this.$refs.link.setAttribute('download', this.fileName+'.csv')
    var url='data:text/csv;charset=utf-8,\ufeff'+encodeURIComponent(csvContent);
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download',  '僵尸網(wǎng)站數(shù)據(jù)表'+'.csv')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) // 下載完成移除元素
    window.URL.revokeObjectURL(url) // 釋放掉blob對象
},
//數(shù)據(jù)遍歷篩選
  computed: {
  headerLabel(){
    var result=[];
    this.checkListShow.forEach(item=>{
      result.push(item.name)
    })
    return result
  },
  headerProp(){
    var result=[];
    this.checkListShow.forEach(item=>{
      result.push(item.prop)   
    })
    return result
  }
 },

4.下載后臺返回文件流數(shù)據(jù)

exportBillingExcel(data, res){
  if (!data) {//如果沒有data數(shù)據(jù)就不進(jìn)行操作
     return
   }
  // 獲取headers中的filename文件名
  let tempName = res.headers['content-disposition'].split(';')[1].split('filename=')[1]
  // iconv-lite解決中文亂碼
  let iconv = require('iconv-lite')
  iconv.skipDecodeWarning = true// 忽略警告
  let fileName = iconv.decode(tempName, 'gbk')
  let blob = new Blob([data], { type: 'application/octet-stream' })//轉(zhuǎn)換成二進(jìn)制對象
  if ('download' in document.createElement('a')) { // 不是IE瀏覽器
    let url = window.URL.createObjectURL(blob)//二進(jìn)制對象轉(zhuǎn)換成url地址
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) // 下載完成移除元素
    window.URL.revokeObjectURL(url) // 釋放掉blob對象
  } else {
    window.navigator.msSaveBlob(blob, fileName)
  }
},

5.下載后臺返回數(shù)據(jù)的.log后綴、.pem后綴文件

downFile(data,name){
            let blob = new Blob([data], {type: "application/octet-stream"});     //下載文件的通用格式
                console.log(window.navigator.msSaveBlob)
                if (window.navigator.msSaveBlob) {
                    window.navigator.msSaveBlob(blob, name+ '.' + 'log');//處理IE下載的兼容性
                } else {
                    let downloadElement = document.createElement('a');
                    let href = window.URL.createObjectURL(blob); //創(chuàng)建下載的鏈接
                downloadElement.href = href;
                    downloadElement.download =  name+ '.' + 'log' ; //下載后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); //點(diǎn)擊下載
                    document.body.removeChild(downloadElement); //下載完成移除元素
                    window.URL.revokeObjectURL(href); //釋放掉blob對象
            }
        }

6.下載圖片

link.setAttribute("download", "");
link.href ="圖片地址路徑";
link.click();

7.下載二進(jìn)制流文件

exporBeianPdf('', { responseType: 'blob' })
        .then(res => {
          this.downBinary(res);
        })
        .catch(() => {
          this.$message.error('導(dǎo)出失敗,請重試。');
        });
// 下載二進(jìn)制文件
    downBinary(res) {
      const data = res.data;
      const tempName = res.headers['content-disposition']
        .split(';')[1]
        .split('filename=')[1];
      /* 兼容ie內(nèi)核,360瀏覽器的兼容模式 */
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        const blob = new Blob([data]);
        window.navigator.msSaveOrOpenBlob(blob, tempName);
      } else {
        /* 火狐谷歌的文件下載方式 */
        var blob = new Blob([data]);
        var downloadElement = document.createElement('a');
        var href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = tempName;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      }
    },

8.base64文件下載

圖片和文件都適用

dwonImageBase64(name,data){
      //let imgData = "data:image/jpg;base64," + ret;  
     //data是帶有"data:image/jpg;base64,"的內(nèi)容的值
       this.downloadFile(name, data);
    },
    downloadFile(fileName, content) {
        let aLink = document.createElement('a');
        let blob = this.base64ToBlob(content); //new Blob([content]);
        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("click", true, true);//initEvent 不加后兩個參數(shù)在FF下會報錯  事件類型,是否冒泡,是否阻止瀏覽器的默認(rèn)行為
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        // aLink.dispatchEvent(evt);
        aLink.click()
   },
    base64ToBlob(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
    },

9.前端實(shí)現(xiàn)批量下載文件

function downloadFile(url) {
var iframe = document.createElement('iframe')
iframe.style.display = 'none' // 防止影響頁面
iframe.style.height = 0 // 防止影響頁面
iframe.src = url
document.body.appendChild(iframe) // 這一行必須,iframe掛在到dom樹上才會發(fā)請求
console.log(iframe)
// 5分鐘之后刪除(onload方法對于下載鏈接不起作用,就先摳腳一下吧)
setTimeout(() =&gt; {
iframe.remove()
}, 5000)
}

10.axios請求responseType為blob時,錯誤數(shù)據(jù)處理

remoteRecoverPost(data) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      getTokenData().then((res) => {
        remoteRecover(data, {
          headers: {
            common: { 'X-CSRFToken': res.data.data.csrf_token },
          },
          responseType: 'blob',
        })
          .then((ress) => {
            loading.close();
            const resData = ress.data;
            const fileReader = new FileReader();
            fileReader.onloadend = () => {
              try {
                const jsonData = JSON.parse(fileReader.result); // 說明是普通對象數(shù)據(jù),后臺轉(zhuǎn)換失敗
                this.$message.warning(jsonData.msg);
              } catch (err) {
                // 解析成對象失敗,說明是正常的文件流
                // 下載文件
                this.exportBillingExcel(ress);
              }
            };
            fileReader.readAsText(resData);
          })
          .catch(() => {
            loading.close();
          });
      });
    },

上面只寫了一種判斷方法,其實(shí)還有一種,如下

 if (resData.type === 'application/json') {
      const jsonData = JSON.parse(fileReader.result) // 說明是普通對象數(shù)據(jù),后臺轉(zhuǎn)換失敗
      // 后臺信息
      console.log(jsonData)
    } else {
      // 下載文件
      his.exportBillingExcel(ress);
    }

以上就是vue實(shí)現(xiàn)各種文檔下載及導(dǎo)出示例的詳細(xì)內(nèi)容,更多關(guān)于vue文檔下載導(dǎo)出的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論