vue3——文件、xlsx下载方法封装

2 篇文章 0 订阅


一、创建一个zipdownload.ts文件

代码如下(示例):

import axios from 'axios'
import { useAdminInfo } from '/@/stores/adminInfo'//获取token
import { getUrl } from './axios'
import { ElLoading } from 'element-plus'
import { ElMessage } from 'element-plus'

const mimeMap = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip'
}
const adminInfo = useAdminInfo()

// const baseUrl = process.env.VUE_APP_BASE_API,
//'str'为下载路径
//'stly'为下载类型(默认xlsx)
//'name'下载文件名称
//'params'为入参
//'method'为请求方式(默认get请求)
export function downLoadZip(str: string, stly: string, name: string, params: Object, method: string) {
  var loading = ElLoading.service({
    lock: true,
    text: "下载中",
    background: "rgba(0, 0, 0, 0.7)",
  })
  var url = getUrl() + str

  let state = stly == "zip" ? mimeMap.zip : mimeMap.xlsx
  if (method == 'post') {
    var data = params;
    axios({
      method: method || 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Batoken': adminInfo.getToken() },
      data
    }).then(response => {
      const res = response.data;
      if (res.type === 'text/html') {
        var enc = new TextDecoder('utf-8');
        res.arrayBuffer().then((buffer: any) => {
          let data = JSON.parse(enc.decode(new Uint8Array(buffer))) || {};
          loading.close();
          return ElMessage({
            message: data.message || '服务器繁忙,请刷新重试',
            type: 'error',
            duration: 5 * 1000
          })
        })
      } else {
        resolveBlob(response, state, name, loading)
      }
    })
  } else {
    axios({
      method: method || 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Batoken': adminInfo.getToken() },
      params
    }).then(response => {
      const res = response.data;
      if (res.type === 'text/html') {
        var enc = new TextDecoder('utf-8');
        res.arrayBuffer().then((buffer: any) => {
          let data = JSON.parse(enc.decode(new Uint8Array(buffer))) || {};
          loading.close();
          return ElMessage({
            message: data.message || '服务器繁忙,请刷新重试',
            type: 'error',
            duration: 5 * 1000
          })
        })
      } else {
        resolveBlob(response, state, name, loading)
      }
    })
  }
}
/** 
* @desc :解析blob响应内容并下载
* @date :
* @param {*} res blob响应内容
* @param {String} mimeType MIME类型
* @author : liangdecheng
**/
export function resolveBlob(res: any, mimeType: string, name: string, loading: any) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  // var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  // var contentDisposition = decodeURI(res.headers['content-disposition'])
  // var result = patt.exec(contentDisposition)
  // var fileName = result[1]
  // fileName = fileName.replace(/\"/g, '')
  if (name == '') {
    let fileName = res.headers['content-disposition']
    var name = decodeURIComponent(fileName).split("*=UTF-8''")[1]
  }

  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', name) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
  loading.close();
}

二、在页面的使用

1.引入方法

代码如下(示例):

 import { downLoadZip } from '/@/utils/zipdownload'

2.使用方法

代码如下(示例):

 // 导出
const exportOk = () => {
    downLoadZip('/goods/exportExcel', 'xlsx', '商品数据', {}, 'post')
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值