vue中request.js中axios请求和(若依)文件通用下载方法封装
1.request.js
javascript
import axios from 'axios'
import { Message, Loading } from 'element-ui'
import { saveAs } from 'file-saver'
// 创建axios实例
const request = axios.create({
// 这里可以放一下公用属性等。
baseURL: '/api', // 用于配置请求接口公用部分,请求时会自动拼接在你定义的url前面。配合跨域使用
withCredentials: true, // 跨域请求时是否需要访问凭证
timeout: 3 * 1000, // 请求超时时间
})
request.interceptors.response.use((response) => {
if(response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer'){
return response.data
}
let { code, msg } = response.data
return response;
}, (error) => {
return Promise.reject(error)
})
let downloadLoadingInstance;
export function download(url, params, filename) {
downloadLoadingInstance = Loading.service({
text: "正在下载数据,请稍候",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)",
})
return request.post(url, params, {
transformRequest: [(params) => {
return tansParams(params)
}],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
responseType: 'blob'
}).then(async (data) => {
const isLogin = await blobValidate(data);
if (isLogin) {
const blob = new Blob([data])
saveAs(blob, filename)
} else {
const resText = await data.text();
const rspObj = JSON.parse(resText);
const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
Message.error(errMsg);
}
downloadLoadingInstance.close();
}).catch((r) => {
Message.error('下载文件出现错误,请联系管理员!')
downloadLoadingInstance.close();
})
}
export async function blobValidate(data) {
try {
const text = await data.text();
JSON.parse(text);
return false;
} catch (error) {
return true;
}
}
export function tansParams(params) {
let result = ''
for (const propName of Object.keys(params)) {
const value = params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && value !== "" && typeof (value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key] !== null && value !== "" && typeof (value[key]) !== 'undefined') {
let params = propName + '[' + key + ']';
var subPart = encodeURIComponent(params) + "=";
result += subPart + encodeURIComponent(value[key]) + "&";
}
}
} else {
result += part + encodeURIComponent(value) + "&";
}
}
}
return result
}
export default request;//记得暴露出去
2.main,js引入该方法(以对象方式引入),并注册
javascript
import {download } from "./utils/request"
Vue.prototype.download = download
3.请求使用(api包下)
javascript
import request from '@/utils/request'
//查询当前目录下的文件
export function getFileList(query){
return request({
url: '/config/sysUpgrade/getFileList',
method: 'get',
params:query
})
}
//上传文件
export function uploadFile(data){
return request({
url: '/config/sysUpgrade/uploadFile',
method: 'post',
data: data
})
}
4.通过下载文件方法使用
download()方法里面需传3个参数
- url为后端给的下载方法的后半段
- params为需要下载的数量
- filename为下载的名字与类型
使用时直接this.download()方法调用
javascript
downloadFile(data){
let file = data.absolutePath;
// "/"分割绝对路径
let list = file.split("/");
// 最后一个就是文件名
let fileName = list[list.length-1];
//调用通用下载方法
this.download(
"config/sysUpgrade/downloadFile",
{
file,
},
fileName
)
}
5.vue.config.js配置解决跨域问题(配置后重启生效)
javascript
module.exports = { //打包后生成的文件夹名称,默认dist
devServer:{ //前端地址
port: 8080, //前段的端口号
proxy: {
'/api': {
target: 'http://localhost:30000',//后端接口地址
changeOrigin: true, //是否允许跨域
pathRewrite: {
'^/api': '' //注册全局路径
}
},
}
}
};