js文件下载几种请求方式,普通请求方式封装
import axios from 'axios'
// axios.defaults.timeout = 30 * 1000;
// axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
import FileSaver from 'file-saver'
import { saveAs } from 'file-saver/FileSaver';
import { reject } from 'lodash';
export function getRequest(url, params, noFilter) {
var newParam
if (!noFilter) {
newParam = params
} else {
newParam = params
}
url += (url.indexOf('?') < 0 ? '?' : '&') + translateParam(newParam)
return new Promise((resolve, reject) => {
return axios.get(url).then(res => {
resolve(res)
})
.catch(err => {
reject(err)
})
})
}
export function postRequest(url, params) {
return new Promise((resolve, reject) => {
axios.post(url, params)
.then(response => {
resolve(response.data);
})
.catch(error => {
reject(error);
})
})
}
export function putRequest(url, params) {
return new Promise((resolve, reject) => {
axios.put(url, params)
.then(response => {
resolve(response.data);
})
.catch(error => {
reject(error);
})
})
}
export function deleteRequest(url, params) {
return new Promise((resolve, reject) => {
axios.delete(url, { data: params })
.then(response => {
resolve(response.data);
})
.catch(error => {
reject(error);
})
})
}
// 下载文件 post
export function downloadPost(params, url, fileName = "") {
return new Promise((resolve, reject) => {
let context = ''
axios({
method: 'post',
headers: {
'Content-type': 'application/json'
},
data: params,
url: url
}).then(res => {
let data = res.data
var FileSaver = require('file-saver');
var file = new File(['\uFEFF' + data], fileName + new Date().getTime() + '.csv', {
type: 'text/plain;charset=utf-8'
});
FileSaver.saveAs(file);
resolve()
})
})
}
// 下载文件 get
export function downloadUrl(url, type = '.csv', name) {
return new Promise((resolve, reject) => {
let context = ''
axios.get(url).then(res => {
// console.log(res)
context = res.data
let file = new File(["\uFEFF" + context], (name ? name : new Date().getTime()) + type, {
type: "text/plain;charset=utf-8"
})
FileSaver.saveAs(file)
resolve()
})
})
}
}
function fileDownload(data, type, fileName) {
let blob = new Blob([data], {
type: 'application/octet-stream'
});
let filename = fileName || 'filename.' + type;
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var blobURL = window.URL.createObjectURL(blob);
var tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', filename);
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}
}
export function downloadExeclPost(url, params, type = 'xlsx', fileName = '') {
let headerConfig = {};
if (!params) {
headerConfig = {
method: 'get',
url: baseURL + url,
headers: {
'Content-type': 'application/json',
Authorization: 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
},
responseType: 'blob'
};
} else {
headerConfig = {
method: 'post',
url: baseURL + url,
headers: {
'Content-type': 'application/json',
Authorization: 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
},
responseType: 'blob',
data: params
};
}
return new Promise((resolve, reject) => {
axios(headerConfig)
.then((res) => {
fileName = fileName ? fileName : new Date().getTime() + '.' + type; // }
fileDownload(res.data, type, fileName);
resolve();
})
.catch((error) => {
alert('网络请求出错!', error);
});
});
}
export function translateTqParam(data) {
let url = ''
for (var k in data) {
let value = data[k] !== undefined ? data[k] : ''
url += `&${k}=${value}`
}
return url ? url.substring(1) : ''
}
export function translateParam(data) {
let url = ''
for (var k in data) {
let value = data[k] !== undefined ? data[k] : ''
url += `&${k}=${encodeURIComponent(value)}`
}
return url ? url.substring(1) : ''
}
export function filterParam(param) {
let obj = {}
for (let key in param) {
if (param[key]) {
obj[key] = param[key]
}
}
return obj
}
使用
import { getRequest, postRequest, downloadPost } from '@/assets/js/request'
import { reqUrl } from './api'
const BaseUrls = {
getVins:reqUrl + 'tripanalyse/getOperatingCarVins'
}
export default {
getVins(params) {
let url = BaseUrls.getVins
try {
const result = postRequest(url, params)
return result
} catch (err) {
return err
}
},
searchTableNames(params) {
let url = BaseUrls.searchTableNames
try {
const result = getRequest(url, params)
return result
} catch (err) {
return err
}
},
getDelete(params) {
let url = BaswUrls.getDelete
try{
const result = deleteRequest(url,params)
return result
}catch(err){
return err
}
}
downloadDetail(params,fileName) {
let url = BaseUrls.downloadDetail
try {
const result = downloadPost(params, url,fileName)
return result
} catch (err) {
return err
}
},
socDistributionDownLoad(params,name){
let url = `${BaseUrls.socDistributionDownLoad}?${translateParam(params)}`
// let type = 'xls'
await downloadUrl(url,'.csv',name)
}
bmsByBatteryDownload(params) {
let url = `${BaseUrls.bmsByBatteryDownload}`
let type = 'xls'
await downloadExeclPost(url, params, type)
}
async infoDownload(params){
let url = `${BaseUrls.infoDownload}?${translateParam(params)}`
let type = 'xls'
await downloadExecl(url, type)
},
}