后端返回文件流 前端处理方法

下载功能

一般后端会返回文件流的形式

前端会收到一堆乱码

前端需要对乱码进行转译  成正常的  

可以先创建一个公共的方法文件,这样就可以在项目的任何地方使用

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);
    },

 

posted @ 2020-09-17 22:04  薄荷zz  阅读(24122)  评论(0编辑  收藏  举报