注意目录和修改相同的字符编码

封装文件下载的方法

1、在封装请求拦截的js文件中需要有以下准备条件:

引入axios,在请求前加上token(这里token是从vuex中取的,这里不再阐述在vuex中的保存方法)

 1 import axios from 'axios'
 2 // 设置post请求头
 3 axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
 4 const http = axios.create({
 5   // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url api的baseUrl
 6   timeout: 30000 // 请求超时时间
 7 })
 8 
 9 http.interceptors.request.use(config => {
10   // 在发送请求之前做些什么 验证token之类的
11   if (store.getters.token) {
12     config.headers['Authorization'] = store.getters.token ? getToken() : store.getters.token
13   }
14   return config
15 }, error => {
16   // 对请求错误做些什么
17   Message.error({ message: '请求超时!' })
18   return Promise.error(error)
19 })

2、文件下载封装函数,然后导出该方法

 1 /**
 2  * Request请求,文件下载
 3  * @param RequestParams Path 请求地址,Method请求方法
 4  * @param urlParams 请求参数拼接在url上
 5  * @param data 请求参数放在请求体
 6  * **/
 7 export function RequsetForDownLoadFile(RequestParams, urlParams, responseData, FileName) {
 8   return new Promise((resolve, reject) => {
 9     http({
10       method: RequestParams.Method,
11       url: RequestParams.Path,
12       params: urlParams, // 请求参数拼接在url上
13       data: responseData, // 请求参数放在请求体
14       responseType: 'blob'
15     })
16       .then(response => {
17         const link = document.createElement('a')
18         const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
19         link.style.display = 'none'
20         link.href = URL.createObjectURL(blob)
21         // link.download = res.headers['content-disposition'] //下载后文件名
22         link.download = FileName // 下载的文件名
23         document.body.appendChild(link)
24         link.click()
25         document.body.removeChild(link)
26         resolve(response.data)
27       }).catch(err => {
28       // 请求失败
29         reject(err)
30    })
31  })

3、在需要下载的页面中导入并调用

import { RequsetForDownLoadFile } from '...'
RequsetForDownLoadFile({ Method: 'get', Path: '/api/pesp-manage-system/fapsysfile/downloadFile' }, { 请求地址后拼接的参数 }, null, 请求体中的参数)

 

posted @ 2022-08-23 09:05  黑使  阅读(129)  评论(0编辑  收藏  举报