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
      })
    }
     
  • 相关阅读:
    Linux 的grep命令显示日志文件指定前后行信息
    Windows下安装MySQL详细教程
    Maven安装配置(Windows10)
    Windows下配置Tomcat服务器
    java环境变量 的配置与详解
    工具使用篇-索引
    Fiddler抓包工具总结
    使用fiddler实现手机抓包
    网络安全-索引
    网络嗅探技术浅析
  • 原文地址:https://www.cnblogs.com/xiaohuizhang/p/14421680.html
Copyright © 2011-2022 走看看