Download file on ajax success node.js

后端 未结 2 1262
死守一世寂寞
死守一世寂寞 2021-01-02 23:28

I am building an app using node.js that needs to allow the user to download a .csv file.

The problem - the app does not send a file to the client as an attachment w

2条回答
  •  生来不讨喜
    2021-01-02 23:45

    There are basically two popular ways to download a file.

    1. Set window.location

    Setting window.location to the download url will download the file.

    window.location = '/path/to/download?arg=1';
    

    A slightly different version of this is to open a new tab with the download path

    window.open('/path/to/download', '_self');
    

    2. Virtual Link Click

    With HTML5, you can specify the download attribute of a link. Clicking the link (even programmatically) will trigger a download of the url. The links don't even need to be part of the DOM, you can make them dynamically.

    var link = document.createElement('a');
    link.href = '/path/to/download';
    link.download = 'local_filename.csv';
    var e = document.createEvent('MouseEvents');
    e.initEvent('click', true, true);
    link.dispatchEvent(e);
    

    This isn't supported in all browsers, so even if you want to use this method, you'll have to drop support for some browsers or fallback to the first method.

    Luckily, this excellent answer references an awesome little js library that does all this already -- http://pixelscommander.com/polygon/downloadjs/#.VrGw3vkrKHv

    downloadFile('/path/to/download');
    

    2-Step Download

    Another convention you'll often see is a two step download, where information is sent to the server at a known url, and the server sends back a generated url or id that can be used to download the file.

    This can be useful if you want the url to be something that can be shared, or if you have to pass a lot of parameters to the download generator or just want to do it via a POST request.

    $.ajax({
        type: 'POST',
        url: '/download/path/generator',
        data: {'arg': 1, 'params': 'foo'},
        success: function(data, textStatus, request) {
            var download_id = data['id'];
            // Could also use the link-click method.
            window.location = '/path/to/download?id=' + download_id;
        }
    });
    

提交回复
热议问题