Download File Using Javascript/jQuery

前端 未结 28 2753
悲&欢浪女
悲&欢浪女 2020-11-21 05:11

I have a very similar requirement specified here.

I need to have the user\'s browser start a download manually when $(\'a#someID\').click();

But

相关标签:
28条回答
  • 2020-11-21 05:55

    To improve Imagine Breaker 's answer, this is supported on FF & IE :

    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    
    function downloadURI(uri, name) {
        var link = document.createElement("a");
        link.download = name;
        link.href = uri;
        link.dispatchEvent(evt);
    }
    

    In other words, just use a dispatchEvent function instead of click();

    0 讨论(0)
  • 2020-11-21 05:57

    I ended up using the below snippet and it works in most browsers, not tested in IE though.

    let data = JSON.stringify([{email: "test@domain.com", name: "test"}, {email: "anothertest@example.com", name: "anothertest"}]);
    
    let type = "application/json", name = "testfile.json";
    downloader(data, type, name)
    
    function downloader(data, type, name) {
    	let blob = new Blob([data], {type});
    	let url = window.URL.createObjectURL(blob);
    	downloadURI(url, name);
    	window.URL.revokeObjectURL(url);
    }
    
    function downloadURI(uri, name) {
        let link = document.createElement("a");
        link.download = name;
        link.href = uri;
        link.click();
    }

    Update

    function downloadURI(uri, name) {
        let link = document.createElement("a");
        link.download = name;
        link.href = uri;
        link.click();
    }
    
    function downloader(data, type, name) {
        let blob = new Blob([data], {type});
        let url = window.URL.createObjectURL(blob);
        downloadURI(url, name);
        window.URL.revokeObjectURL(url);
    }
    
    0 讨论(0)
  • 2020-11-21 05:57

    I don't know if the question is just too old, but setting window.location to a download url will work, as long as the download mime type is correct (for example a zip archive).

    var download = function(downloadURL) {
    
       location = downloadURL;
    
    });
    
    download('http://example.com/archive.zip'); //correct usage
    download('http://example.com/page.html'); //DON'T
    
    0 讨论(0)
  • 2020-11-21 05:58

    Firefox and Chrome tested:

    var link = document.createElement('a');
    link.download = 'fileName.ext'
    link.href = 'http://down.serv/file.ext';
    
    // Because firefox not executing the .click() well
    // We need to create mouse event initialization.
    var clickEvent = document.createEvent("MouseEvent");
    clickEvent.initEvent("click", true, true);
    
    link.dispatchEvent(clickEvent);
    

    This is actually the "chrome" way solution for firefox (I am not tested it on other browsers, so please leave comments about the compilability)

    0 讨论(0)
提交回复
热议问题