zoukankan      html  css  js  c++  java
  • 通过Blob对象下载文件的方法

        此方法主要用于我们将某些信息,下载成固定的文件格式,如word或记事本等等,

    核心的方法有两个一个是Blob构造函数,一个是window.URL.createObjectURL()

    对于Blob官方解释如下
     语法
    var aBlob = new Blob( array, options );

    参数Array:是一个由ArrayBuffer ArrayBufferView Blob Blob 对象表示一个不可变、原始数据的类文件对象。DOMString 等对象构成的 Array ,或者其他类似对象的混合体,它将会被放进 Blob 。DOMStrings会被编码为UTF-8。

    参数options:
    1、type 用来表示文件类型,例如 'text/json' 代表一个JSON文件,'text/html'代表一个HTML文件。

    2、endings 默认值为"transparent",用于指定包含行结束符 的字符串如何被写入。 它是以下两个值中的一个: "native",表示行结束符会被更改为适合宿主操作系统文件系统的换行符; "transparent",表示会保持blob中保存的结束符不变。

    URL.createObjectURL() 
    静态方法会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
    Vue.prototype.shandlerLocationDown = (_url, title, lastName = '.txt', typeMethod = 'get', params = {}) => {
        axios({                                           文件的后缀名,根据不同文件更换
            method: 'get',
            url: _url,
            responseType: 'blob',
            data: params,
        }).then((res) => {
            const data = res.data;
            if (!data) {
                return;
            }
            let blob = new Blob([data], {
                // type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8',
                // 'Content-type': 'application/octet-stream',
             type:'text/plain'    不同文件的MIME类型进行更换      
            });
            let url = window.URL.createObjectURL(blob);
            let fileName = lastName != null ? title + lastName : title;
            if ('download' in document.createElement('a')) {//通过 使用a标签的download方法下载文件
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                a.style.display = 'none';
                document.body.appendChild(a);
                a.click();
                URL.revokeObjectURL(a.href);    URL.revokeObjectURL() 静态方法用来释放一个之前通过调用 URL.createObjectURL() 创建的已经存在的 URL 对象。当你结束使用某个 URL 对象时,应该通过调用这个方法来让浏览器知道不再需要保持这个文件的引用了。
                document.body.removeChild(a);
            } else {
                navigator.msSaveBlob(blob, fileName);
            Internet Explorer 10 的 msSaveBlob 和 msSaveOrOpenBlob 方法允许用户在客户端上保存文件,方法如同从 Internet 下载文件,这是此类文件保存到“下载”文件夹的原因
            }
        });
    };
    MIME的类别表 https://www.w3school.com.cn/media/media_mimeref.asp

  • 相关阅读:
    ueditor后台配置项返回格式出错,上传功能将不能正常使用
    js控制多层单选,多选按钮,做隐藏操作
    js控制全屏及退出全屏
    springboot2.0jar包启动异常
    第九篇: 高可用的服务注册中心
    第八篇: 服务链路追踪(Spring Cloud Sleuth)
    第七篇: 消息总线(Spring Cloud Bus)
    第六篇: 分布式配置中心(Spring Cloud Config)
    第五篇: 路由网关(zuul)
    NodeJS
  • 原文地址:https://www.cnblogs.com/ybhome/p/13534071.html
Copyright © 2011-2022 走看看