封装utils工具
1:utils文件
// 此为封装的解析文件流的工具
// fileName传的是你要导出格式的文件后缀
export function exportDataByBlob(data, options, fileName) {
const blob = new Blob([data], options)
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
downloadElement.href = href
downloadElement.download = fileName
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)
}
2:导入的接口文件
注意如果后端直接给一个文件流的形式例如这样:
直接response中响应的就是一个svg文件的代码
我的这个接口是get请求
index.js
// 组件下载接口(此例子中是svg文件流,由于接口封装的只允许code为0的时候可以继续执行,而此接口响应的就是一个svg文件的代码,需要用axios中的transformResponse,对接口进行处理)
export function postTemplateDownload(params) {
return javaHttpRequest({
url: `/template-center/admin/component/download/${params.id}`,
method: 'get',
// 此部分代码是处理接口相应的数据
transformResponse: [
function (response) {
if (response.code) {
return response
} else {
return { data: response, code: 0 }
}
}
],
params
})
}
3:vue文件引用转换的方法
// 因为我下载的是svg,所以后缀加的是svg
download(id) {
postTemplateDownload({ id: id }).then(res => {
exportDataByBlob(res, { type: 'image/svg+xml' }, 'component_' + id + '.svg')
})
},
总结:到这就结束啦,可以直接引用工具进行导出。