JS - 下载文件

1.下载new file() 生成的对象文件

首先创建一个a标签,href属性赋值为要下载文件对象的URL,然后调用a标签上的click()方法就可以下载file文件到本地了。

关于文件对象的URL怎么获得,这里要用到URL.createObjectURL(object)方法,参数object为一个File对象或者Blob对象,返回值就是一个UTF-16字符串,可以当作a标签的href属性值来使用。注意:在使用完URL.createObjectURL()方法之后,要用URL.revokeObjectURL(url)来释放掉。参数url为刚才生成的那个UTF-16字符串。
参考

实例代码

let file = new File([data], "fileName.obj");//创建一个file文件
//let blob = new Blob([data]);
let aTag = document.createElement('a');//创建一个a标签
aTag.download = file.name;
let href = URL.createObjectURL(file);//获取url
aTag.href = href;
aTag.click();
URL.revokeObjectURL(href);//释放url
  1. 后台服务器有静态资源且有固有的文件名称(GET方式下载文件)
window.location.href="http://www.域名/template.xlsx(文件名)"
  1. 后台返回文件流
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
// 传参 => 调接口  => 下载
axios.post(请求路径URL, {参数Params}, {
            responseType: 'blob'
          }).then(function(res){
            var blob = res.data;
           // FileReader主要用于将文件内容读入内存
            var reader = new FileReader();
            reader.readAsDataURL(blob);
            // onload当读取操作成功完成时调用
            reader.onload = function(e) {
              var a = document.createElement('a');
              // 获取文件名fileName
              var fileName = res.headers["content-disposition"].split("=");
              fileName = fileName[fileName.length - 1];
              fileName = fileName.replace(/"/g, "");
              a.download = fileName;
              a.href = e.target.result;
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
            }
          });
  1. form 表单提交
var exportForm = $('<form action="/api/cert/download" method="post">\
        <input type="hidden" name="ids" value="'+参数ids值+'"/>\
        </form>');
       $(document.body).append(exportForm);
       exportForm.submit();
       exportForm.remove();


版权声明:本文为qq_35389653原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。