Download File Using Javascript/jQuery

前端 未结 28 2751
悲&欢浪女
悲&欢浪女 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:52
    function downloadURI(uri, name) 
    {
        var link = document.createElement("a");
        // If you don't know the name or want to use
        // the webserver default set name = ''
        link.setAttribute('download', name);
        link.href = uri;
        document.body.appendChild(link);
        link.click();
        link.remove();
    }
    

    Check if your target browser(s) will run the above snippet smoothly:
    http://caniuse.com/#feat=download

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

    2019 modern browsers update

    This is the approach I'd now recommend with a few caveats:

    • A relatively modern browser is required
    • If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(resp => resp.blob())
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        // the filename you want
        a.download = 'todo-1.json';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        alert('your file has downloaded!'); // or you know, something with better UX...
      })
      .catch(() => alert('oh no!'));

    2012 original jQuery/iframe/cookie based approach

    I have created the jQuery File Download plugin (Demo) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:

    • Very easy to setup with nice visuals (jQuery UI Dialog, but not required), everything is tested too

    • User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications

    • successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation

    • In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this. Hope this helps someone!

    Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

    $.fileDownload('some/file.pdf')
        .done(function () { alert('File download a success!'); })
        .fail(function () { alert('File download failed!'); });
    
    0 讨论(0)
  • 2020-11-21 05:53
    let args = {"data":htmlData,"filename":exampleName}
    

    To create a HTMl file and download

    window.downloadHTML = function(args) {
    var data, filename, link;
    var csv = args.data;
    if (csv == null) return;
    filename = args.filename || 'report.html';
    data = 'data:text/html;charset=utf-8,' + encodeURIComponent(csv);
    console.log(data);
    link = document.createElement('a');
    link.setAttribute('href', data);
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);}
    

    To create and download a CSV

    window.downloadCSV = function(args) {
    var data, filename, link;
    var csv = args.data;
    if (csv == null) return;
    filename = args.filename || 'report.csv';
    if (!csv.match(/^data:text\/csv/i)) {
        csv = 'data:text/csv;charset=utf-8,' + csv;
    }
    data = encodeURI(csv);
    link = document.createElement('a');
    link.setAttribute('href', data);
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    

    }

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

    I know I'm late for the party, but I'd like to share my solution which is variation of Imagine Breaker's solution above. I tried to use his solution, because his solution seems most simple and easy to me. But like other said, it didn't work for some browsers, so I put some variation on it by using jquery.

    Hope this could help someone out there.

    function download(url) {
      var link = document.createElement("a");
      $(link).click(function(e) {
        e.preventDefault();
        window.location.href = url;
      });
      $(link).click();
    }
    
    0 讨论(0)
  • 2020-11-21 05:54

    Works on Chrome, Firefox and IE8 and above.

    var link=document.createElement('a');
    document.body.appendChild(link);
    link.href=url ;
    link.click();
    
    0 讨论(0)
  • 2020-11-21 05:54

    Excelent solution from Corbacho, I just adapted to get rid o the var

    function downloadURL(url) {
        if( $('#idown').length ){
            $('#idown').attr('src',url);
        }else{
            $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
        }
    }
    
    0 讨论(0)
提交回复
热议问题