当前位置:   article > 正文

vue实现文件下载的2种方式_vue 下载文件

vue 下载文件

iframe / a

iframe、a标签下载文件都是调用浏览器默认下载行为

iframe闭合标签,会创建包含另个文档的内联框架,通过iframe实现文件(附件)的下载,隐藏iframe,当点击事件触发的时候,动态设置src就能实现文件下载功能

元素(或称锚元素)可以通过它的 href 属性创建通向其他网页、文件、同一页面内的位置、电子邮件地址或任何其他 URL 的超链接。

代码

<template>
  <div id="app" class="container">
    <!-- <img alt="Vue logo" src="./assets/logo.png" style="width: 40px; margin-left: 145px; margin-top: 40px; margin-bottom: 7px;"> -->
    <!-- <UploadPhoto></UploadPhoto> -->


    <div style="margin: 50px 0px; display: flex;">
      <div style="margin-right: 10px; color: grey;">
        <div>通过iframe、a标签实现文件下载功能</div>
        <div>点击按钮下载 'QQ9.7.1.28934.exe' 文件</div> 
      </div>
      <div>
        <el-button type="primary" @click="loadFile">点击下载</el-button>
      </div>
    </div>

  </div>
</template>

<script>


export default {
  name: 'App',
  components: {
    // Demo
  },
  data() {
    
  },
  created() {
    //
  },
  methods: {
    // iframe标签
    loadFile() {
      console.log("asda")
      let url = 'https://dldir1.qq.com/qqfile/qq/PCQQ9.7.1/QQ9.7.1.28934.exe';
      const iframe = document.createElement('iframe'); // 创建一个HTML 元素
      iframe.style.display = 'none'; // 隐藏iframe 防止影响页面      
      iframe.style.height = 0; // 高度设置0 防止影响页面      
      iframe.src = url;// 下载链接       
      document.body.appendChild(iframe); // 这一行必须,iframe挂在到dom树上才会发请求      // 5分钟之后删除
      setTimeout(() => { iframe.remove(); }, 5 * 60 * 1000);
      console.log("111asda")
    },
    // a标签
    loadFile2() {
      const a = document.createElement('a'); // 创建一个HTML 元素
      let url = 'https://dldir1.qq.com/qqfile/qq/PCQQ9.7.1/QQ9.7.1.28934.exe';
      a.setAttribute('download', ''); //download属性
      a.setAttribute('href', url); // href链接
      a.click(); // 自执行点击事件
    }
  }

}
</script>

<style>
 .el-input {
  width: 200px !important; 
 }
</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/683393
推荐阅读
相关标签
  

闽ICP备14008679号