Download File Using Javascript/jQuery

前端 未结 28 2939
悲&欢浪女
悲&欢浪女 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: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!'); });
    

提交回复
热议问题