vue3中,下载模板(一)
效果
1
2
3
1、页面
index.vue
<el-button type="primary" @click="fileDownload">下载模板</el-button>
<script setup>
import { exportByPage} from '@/api/variousUnits/expert'
import { downloadFileCom } from '@src/hooks/useFolesUtils.js'
// 下载
const fileDownload = async () => {
await exportByPage().then((res) => {
downloadFileCom(res, '指南编制专家模板')
})
}
</script>
2、接口
src\app\science\api\variousUnits\expert.js
//专家推荐-模板导出下载
export const exportByPage = (data) => {
return request({
url: `${sciencePostUrl}/recomd/template`,
method: 'post',
data,
responseType: 'blob',
})
}
3、file流文件处理
src\hooks\useFolesUtils.js
const path = require('path')
import { ref } from 'vue'
export const downloadFileCom = (res, fileName) => {
const extname = path.extname(fileName)
if (res && res.data) {
const blob = ref(null)
switch (extname) {
case '.xlsx':
blob.value = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})
break
case '.doc':
blob.value = new Blob([res.data], {
type: 'application/msword',
})
break
case '.docx':
blob.value = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
})
break
case '.rar':
blob.value = new Blob([res.data], {
type: 'application/x-rar-compressed',
})
break
case '.zip':
blob.value = new Blob([res.data], {
type: 'application/zip,charset=utf-8',
})
break
case '.pdf':
blob.value = new Blob([res.data], {
type: 'pplication/pdf',
})
break
case '.jpg':
blob.value = new Blob([res.data], {
type: 'image/jpeg',
})
break
default:
blob.value = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})
break
}
console.log(blob.value, ' blob.value ')
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob.value) //创建下载的链接
downloadElement.href = href
downloadElement.download = fileName.toString().trim() //下载后文件名
document.body.appendChild(downloadElement)
downloadElement.click() //点击下载
document.body.removeChild(downloadElement) //下载完成移除元素
window.URL.revokeObjectURL(href) //释放掉blob对象
} else {
throw '下载文件无返回值'
}
}