zoukankan      html  css  js  c++  java
  • 前端实现文件下载所有方式

    一.a标签完成

    <a href="文件链接" download='下载文件名'></a>
    <--!但是其中的download对应音频文件和视频文件无效-->
    

    二.js实现下载

    <script>
        const a = document.createElement('a');
        a.setAttribute('href', '文件链接');    //a.href='文件链接'
        a.setAttribute('download', '文件名');   //a.download='文件名'
        a.click();
    </script>
    

    三.js中ajax实现音频或者视频不跳转进行文件下载

    写代码的思路

    先请求音频的链接,再把返回值转换成二进制,再根据他二进制对象生成新链接,再创建a标签,点击a标签

    //这是vue里面的写的普通页面也差不多
    <script>
        this.$axios({
        method: 'get',
        url: row.src,
        responseType: 'blob'  //这个不能少,让response二进制形式,如果你按照网上教程不设置这个将返回值进行BLOB([])进行处理可能会出现解析错误
    }).then(response => {
        const href = URL.createObjectURL(response.data); //根据二进制对象创造新的链接
        const a = document.createElement('a');
        a.setAttribute('href', href);
        a.setAttribute('download', row.title);
        a.click();
        URL.revokeObjectURL(href);
    }
    </script>
    

    四.fetch实现

    //原理和ajax一模一样
    function request() {
      fetch('<接口地址>', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: '<请求参数:json字符串>',
      })
        .then(res => res.blob())
        .then(data => {
          let blobUrl = window.URL.createObjectURL(data);
          download(blobUrl);
        });
    }
     
    function download(blobUrl) {
      const a = document.createElement('a');
      a.download = '<文件名>';
      a.href = blobUrl;
      a.click();
    }
     
    request();
    
  • 相关阅读:
    cas 单点登录服务端客户端配置
    POI 导出excel
    关于小米手机刷机亲尝
    C#对本地文件重命名--适用于下载的图片、电视剧等奇怪名字的重命名
    泛型List<T>与非泛型ArrayList
    设置一键启动多文件
    网页显示电子表
    插入sql语句01值时,在数据库中的查询时显示为1
    C#面向对象--继承
    SqlServer数据库查询不同字段-年龄段分析
  • 原文地址:https://www.cnblogs.com/pythonywy/p/11671303.html
Copyright © 2011-2022 走看看