vue3中,下载模板(二)——file流文件处理-简约版 & 接口responseType-blob
效果
1、页面
index.vue
<el-button type="primary" @click="fileDownload">下载模板</el-button>
<script setup>
import {fileDownloadData} from '@/api/organization/project'
import { downLoadxls } from '@src/utils/util'
// 下载
const fileDownload = () => {
// await getFileDownload().then((res) => {
// window.open(res)
// })
fileDownloadData().then((res) => {
downLoadxls(res, '规划计划')
})
}
</script>
2、接口
src\app\plan\api\organization\project.js
//模板下载-规划计划
export const fileDownloadData = () => {
return request({
url: `${plan}/prjPlan/fileDownload`,
method: 'get',
responseType: 'blob',
})
}
3、file流文件处理-简约版
src\utils\util.js
//文件流导出数据处理
export const downLoadxls = (res, fileName) => {
let name = fileName
if (res.headers['content-disposition']) {
const contentDisposition = res.headers['content-disposition'].split('=')
name = (contentDisposition && decodeURI(contentDisposition[1])) || ''
}
const file = new File([res.data], name, res.data)
const href = URL.createObjectURL(file)
const aTag = document.createElement('a')
aTag.download = file.name
aTag.target = '_blank'
aTag.href = href
aTag.click()
URL.revokeObjectURL(href)
}