fuliqi
2024-01-24 29c1e7eb5ac16e90d8991a86c1c071bc312ec8d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
 
/**
 *文件下载
 */
export function downloadFile (config, type = 'application/vnd.ms-excel') {
  return axios({
    method: config.Method ? 'get' : 'post',
    url: `${process.env.VUE_APP_CURRENTMODE === 'development' ? '/api' : process.env.VUE_APP_API_BASE_URL}${config.url}`,
    data: config.data, // 传递参数
    params: config.Method ? config.data : undefined,
    responseType: 'blob', // 表明返回服务器返回的数据类型
    // 设置请求头信息
    headers: {
      Authorization: 'Bearer ' + store.state.token
    },
    // `onUploadProgress` 允许为上传处理进度事件
    onUploadProgress: config.onUploadProgress,
    onDownloadProgress: config.onDownloadProgress
  }).then(response => {
    if (!response.headers['content-disposition']) {
      Message({
        message: '导出失败!',
        type: 'error'
      })
      return
    }
    return new Promise(function (resolve, reject) {
      if (response.data) {
        const blob = new Blob([response.data], { type })
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        // response.headers['content-disposition'].split(';')[1].split('=')[1]
        if (config.type !== 'varied') {
          link.setAttribute('download', config.fileName + (config.type ? config.type : '.xls'))
        } else {
          link.setAttribute('download', config.fileName)
        }
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        resolve(1)
        Message({
          message: '导出成功!',
          type: 'success'
        })
      } else {
        reject(response.msg)
      }
    })
  }).catch(error => {
    Message({
      message: '导出失败!',
      type: 'error'
    })
    // 请求失败,
    console.log(error)
  })
}