tansParams
/**
* 参数处理
* @param {*} params 参数
*/
export function tansParams(params) {
let result = ''
Object.keys(params).forEach((key) => {
if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
}
})
return result
}
通用下载方法
// 通用下载方法
export function download(url, params, filename) {
return service.post(url, params, {
transformRequest: [(params) => {
return tansParams(params)
}],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
responseType: 'blob'
}).then((data) => {
const content = data
const blob = new Blob([content])
if ('download' in document.createElement('a')) {
const elink = document.createElement('a')
elink.download = filename
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href)
document.body.removeChild(elink)
} else {
navigator.msSaveBlob(blob, filename)
}
}).catch((r) => {
console.error(r)
})
}
main.js
import { download } from '@/utils/request'
Vue.prototype.download = download
使用
/** 导出按钮操作 */
handleExport() {
this.download('schedule/job/log/export', {
...this.queryParams
}, `log_${new Date().getTime()}.xlsx`)
}
转载请注明:有爱前端 » 通用下载方法