zoukankan      html  css  js  c++  java
  • 后端返回文件流 前端处理方法

    下载功能

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

    前端会收到一堆乱码

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

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

    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 = `参拍日期,项目名称
    `;
          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 += "
    ";
          }
          //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);
        },
  • 相关阅读:
    写了个限制文本框输入最大长度的jquery插件
    A2D JS框架
    在.Net中执行js
    C# Socket的粘包处理
    分布式EventBus的Socket实现
    读写分离子系统
    缓存子系统如何设计(Cachable tag, Memcache/redis support, xml config support, LRU/LFU/本地缓存命中率)
    pip install在Windows下报错解决
    Centos 6.9安装配置MongoDB
    Centos6.9安装Node.js+npm爬坑
  • 原文地址:https://www.cnblogs.com/zfdbk/p/13433946.html
Copyright © 2011-2022 走看看