Download File Using Javascript/jQuery

前端 未结 28 2978
悲&欢浪女
悲&欢浪女 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条回答
  •  Happy的楠姐
    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);
    }
    

提交回复
热议问题