【前端开发】常见文件下载组件封装
1、组件源码
<!-- 功能:下载一个ajax返回的流数据 --> <template> <div> <a ref="autoDownload" :href="url" :download="filename" :style="downloadStyle" class="download"> {{ displayName }} </a> </div> </template> <script lang="ts"> import { Vue, Component, Prop, Watch } from 'vue-property-decorator' @Component({}) export default class extends Vue { @Prop() public filename!: string @Prop({ default: '点击下载' }) public displayName!: string @Prop() public readonly data!: object @Prop({ default: true }) public hidden!: boolean public content: any = undefined public url = '' public downloadStyle: object = this.hidden === false ? {} : { display: 'none' } @Watch('data') public downloadProcess(data: Blob) { if (data === undefined) return if (!(data instanceof Blob)) { // console.warn('XX-download warning: \r\n当前文件数据内容不合法,请确保为stream') return } if (data.size <= 0) { // console.warn('XX-download warning: \r\n文件内容不能为空') } this.url = URL.createObjectURL(new Blob([data], { type: data.type })) const autoDownload = this.$refs['autoDownload'] as HTMLElement this.$nextTick(() => { autoDownload.click() }) } public download(data: Blob) { this.downloadProcess(data) } } </script> <style lang="scss" scoped> .download { text-decoration: none; } </style>
2、使用方式
引入组件
<downLoad :filename="fileName" :data="fileData" /> import downLoad from '@/components/Download/index.vue' @Component({ name: 'Receive-Va-outputForm', components: { downLoad } })
接口拿到数据流赋值到下载组件
async handleFileClick(file: any) { this.fileName = file.description try { let res = await downloadReportTemplate(reportDefineId) this.fileData = res.data } catch {} }
3、接口注意加responseType类型
// 下载报表模板 export function downloadReportTemplate(reportDefineId: string) { return request({ responseType: 'blob', method: 'get', url: 'admin/reportTemplate/template/' + reportDefineId, baseURL: buseBaseUrl }) }
本文来自博客园,作者:JeckHui;
个人主页:前端实用站点推荐; 热榜资讯早读:热榜资讯-导航;
转载请注明原文链接:https://www.cnblogs.com/xiaohuizhang/p/14421680.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)