下载文件时使用,传入url跟Name即可:

144 阅读1分钟
    downloadFile(url, fileName) {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.onload = function () {
            // 请求完成
            let blob = this.response;
            // 创建隐藏的可下载链接
            let eleLink = document.createElement('a');
            eleLink.download = fileName;
            eleLink.style.display = 'none';
            // eleLink.href = url
            eleLink.href = URL.createObjectURL(blob);
            // 触发点击
            document.body.appendChild(eleLink);
            eleLink.click();
            // 然后移除
            document.body.removeChild(eleLink);
        };
        xhr.ontimeout = function (e) {
            //下载超时请重试
            console.log(e);
            // _this.$message.error('下载超时请重试')
        };
        xhr.onerror = function (e) {
            //下载出错
            console.log(e);
            // _this.$message.error('下载出错,请联系管理员')
        };
        // 发送ajax请求
        xhr.send();
    },