美文网首页
vue浏览器下载文件

vue浏览器下载文件

作者: 嘴角上扬h | 来源:发表于2022-02-18 15:42 被阅读0次
export default{
    install(Vue,option){
        Vue.prototype.downloadFile = function(fileData){
            let fileName = ''
            if(!fileData || !fileData.url){
                this.$message({
                    type: "warning",
                    message: "暂无文件地址!",
                    duration: 2000,
                });
                return false
            }
            //名称
            if(fileData.name){
                fileName = fileData.name
            }else{
                let index = fileData.url.lastIndexOf("/"); //(考虑严谨用lastIndexOf(".")得到)得到"."在第几位
                fileName = fileData.url.substring(index+1); //截断"."之前的,得到后缀
            }
            fetch(fileData.url,{headers: {'Accept':'application/octet-stream'}}).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, filename);  //兼容ie10
                }else{
                    let a = document.createElement('a');
                    document.body.appendChild(a) //兼容火狐,将a标签添加到body当中
                    let url = window.URL.createObjectURL(blob);   // 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
                    a.href = url;
                    a.download = fileName;
                    a.target='_blank'  // a标签增加target属性
                    a.click();
                    a.remove()  //移除a标签
                    window.URL.revokeObjectURL(url);
                }
            })
        }
    }
}

相关文章

网友评论

      本文标题:vue浏览器下载文件

      本文链接:https://www.haomeiwen.com/subject/kcjylrtx.html