使用Javascript下载文件/URL [英] Download file/url using Javascript

查看:57
本文介绍了使用Javascript下载文件/URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过创建链接并单击它来使用javascript自动下载文件.可以,但是使用download属性指定文件将具有的名称无效.

I am trying to automatically download a file using javascript by creating a link and the clicking it. That works but using the download attribute, to specify the name the file will have, does not work.

我正在使用下面的代码

var a = document.createElement("a")
a.download = "hellooo.png"
a.href = "http://icons.iconarchive.com/icons/yellowicon/game-stars/256/Mario-icon.png";
a.click();

有没有办法使这项工作有效?

Is there a way to make this work?

推荐答案

这是我使用XMLHttpRequest的代码,已在IE10 +,firefox和Chrome中进行了测试

Here is my code using XMLHttpRequest ,tested in IE10+ , firefox ,and Chrome

function download(url, fileName) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';

    xhr.onprogress = function(event) {
        if (event.lengthComputable) {
            var percentComplete = (event.loaded / event.total)*100;
            //yourShowProgressFunction(percentComplete);
        } 
    };

    xhr.onload = function(event) {
        if (this.status == 200) {
            _saveBlob(this.response, fileName);
        }
        else {
            //yourErrorFunction()
        }
    };

    xhr.onerror = function(event){
        //yourErrorFunction()
    };

    xhr.send();
}


function _saveBlob(response, fileName) {
    if(navigator.msSaveBlob){
        //OK for IE10+
        navigator.msSaveBlob(response, fileName);
    }
    else{
        _html5Saver(response, fileName);
    }
}

function _html5Saver(blob , fileName) {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    var url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    document.body.removeChild(a);
}

这篇关于使用Javascript下载文件/URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆