1.导出组件封装
import { Message } from 'element-ui'
import qs from 'qs'
import store from '@/store'
const Export = function(obj, filename) {
this.obj = obj
this.filename = filename
}
Export.prototype.exportFile = function() {
// eslint-disable-next-line no-undef
cwsProgress.set({ start: 5 }).start()
function exportFile(fileName, obj, authorization) {
if (obj.method === 'get' && obj.data) {
var params = Object.keys(obj.data).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(obj.data[key])
}).join('&')
obj.url += '?' + params
}
const xhr = new XMLHttpRequest()
xhr.open(obj.method || 'POST', obj.url, true)
xhr.setRequestHeader('Content-type', (obj.headers ? obj.headers['Content-Type'] : '') || 'application/json')
xhr.responseType = 'arraybuffer'
if (authorization) {
xhr.setRequestHeader('authorization', authorization)// 请求头中的验证信息等(如果有)
xhr.setRequestHeader('requestId', Math.floor(Math.random() * 100000000) + new Date().getTime())
}
xhr.onload = function() {
obj.success && obj.success()
// eslint-disable-next-line no-undef
cwsProgress.end()
if (this.status === 200) {
const type = xhr.getResponseHeader('Content-Type')
const blob = new Blob([this.response], { type: type })
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, fileName)
} else {
const URL = window.URL || window.webkitURL
const objectUrl = URL.createObjectURL(blob)
if (fileName) {
const a = document.createElement('a')
if (typeof a.download === 'undefined') {
window.location = objectUrl
} else {
a.href = objectUrl
a.download = fileName
document.body.appendChild(a)
a.click()
a.remove()
}
} else {
window.location = objectUrl
}
}
} else {
var b = new Blob([this.response])
var r = new FileReader()
r.readAsText(b, 'utf-8')
r.onload = function() {
// console.log()
const a = JSON.parse(r.result)
Message({
message: a.message,
type: 'error',
duration: 3 * 1000
})
}
}
}
if (obj.headers && (obj.headers['Content-Type'] === 'application/x-www-form-urlencoded')) {
xhr.send(qs.stringify(obj.data))
} else {
xhr.send(JSON.stringify(obj.data))
}
}
exportFile(this.filename, this.obj, 'bearer ' + store.getters.token)
}
export default Export
2.方法
export function downImgCode(url, data, name) { new Export({ url: `${url}`, method: 'GET', data: data }, name).exportFile() }
3.使用
this.$service.common.downSceneCode(this.info.preAllocationCodeUrl, {}, `${this.name}二维码.png`)