1. 程式人生 > 實用技巧 >後端返回檔案流 前端處理方法

後端返回檔案流 前端處理方法

下載功能

一般後端會返回檔案流的形式

前端會收到一堆亂碼

前端需要對亂碼進行轉譯 成正常的

可以先建立一個公共的方法檔案,這樣就可以在專案的任何地方使用

utils.js

import { getToken } from '@/common/utils/common/auth';
import axios from 'axios';
import { getLocalItem, Constants } from '@/common/utils/common/cache';
export function $fileDownload(url, config = {}) {
    let downloadUrl 
= process.env.VUE_APP_LIMS + url; let method = config.method || 'get'; axios .request({ url: downloadUrl, method: method, headers: { Authorization: getToken(), 'Content-Type': 'application/json', 'User-Lang': getLocalItem(Constants.LOCALE) }, data: config.data, responseType:
'blob' }) .then( response => { console.log(response) let filename = response.headers['content-disposition']; // 取出檔名字 console.log(filename) if (filename) { let index = filename.indexOf('fileName='); console.log(index)
if (index >= 0) { console.log(index) filename = filename.substr(index + 9); filename = decodeURI(filename); } console.log(index) filename = filename.substr(index + 21); filename = decodeURI(filename); } let fileDownload = require('js-file-download'); fileDownload(response.data, filename); if (typeof config.resolve === 'function') { config.resolve(); } }, error => { let hasError = true; if (error.response) { const status = error.response.status; if (status === 401) { hasError = false; } } if (hasError) { this.$showError('下載出錯,請稍後再試'); } if (typeof config.reject === 'function') { config.reject(); } } ); }

頁面使用

import{$fileDownload}from"@/modules/lims/utils/utils";
  async  tipsZPGCalendar() {

      // let data = {
      //     startDate: this.startDate,
      //     endDate: this.endDate,
      //   }
      // let config = {
      //   data: data,
      //   resolve: () => {
     
      //   },
      //   reject: () => {
    
      //   },
      // };
      let url = '/capitalPlan/reportSearchZPGCalendar?startDate=' + this.startDate + '&endDate=' + this.endDate
      const hh = await  $fileDownload(url)
    
     
    
      
    
    },

   handleClick() {
      let str = `參拍日期,專案名稱\n`;
      for (let i = 0; i < this.list.length; i++) {
        let landProjects = [];
        for (let j = 0; j < this.list[i].landProjects.length; j++) {
          landProjects.push(this.list[i].landProjects[j]["projectName"]);
        }
        landProjects.join(",");
        str += `${this.list[i]["dateStr"]},${landProjects}`;
        str += "\n";
      }
      //encodeURIComponent解決中文亂碼
      let uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
      //通過建立a標籤實現
      let link = document.createElement("a");
      link.href = uri;
      //對下載的檔案命名
      link.download = `參拍日曆資料表${this.year}-${this.month}.xls`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },