zoukankan      html  css  js  c++  java
  • 【前端开发】常见文件下载组件封装

    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: 
    当前文件数据内容不合法,请确保为stream')
          return
        }
        if (data.size <= 0) {
          // console.warn('XX-download warning: 
    文件内容不能为空')
        }
        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
      })
    }
     
  • 相关阅读:
    项目管理--项目干系人与组织
    项目管理--项目生命周期概述
    项目管理--简介
    算法学习之冒泡排序,6174问题
    算法学习之基础题
    PHP5.3.8连接Sql Server SQLSRV30
    解决:安装SQl 2008为SQL Server代理服务提供的凭据无效
    Sublime Text2不自动打开最近的项目
    unix网络编程之简介
    算法学习之函数
  • 原文地址:https://www.cnblogs.com/xiaohuizhang/p/14421680.html
Copyright © 2011-2022 走看看