Receiving a .xls file using Ajax jquery POST

前端 未结 2 936
囚心锁ツ
囚心锁ツ 2021-02-06 19:57

I\'m attempting to return an Excel file through a Ajax POST to the server, the server generates the .xls file, however it doesn\'t pass through to the front end, i

相关标签:
2条回答
  • 2021-02-06 20:36

    You cannot use AJAX to download files from the server. The browser will deny Javascript from accessing the user's filesystem.

    You should look at providing a "download servlet" on your server side, which can set the appropriate headers to ensure the browser downloads the file or prompts the user to save a stream it is receiving from the Server.

    As noted here, you could also certain plugins that can provide you an AJAX-like experience. Internally they might be using iFrames to simulate AJAX-like behavior.

    0 讨论(0)
  • 2021-02-06 20:37

    Try this http://jsfiddle.net/abLeR/

    It downloads a tar file using hidden iFrame and ajax. Same can be used for the xls file.

    HTML

    <a class="download" href="http://ftp.neu.edu.cn/mirrors/eclipse/technology/epp/downloads/release/kepler/SR1/eclipse-java-kepler-SR1-linux-gtk.tar.gz">Download</a>
    <span style="display:none;" class="loading">Loading...</span>
    

    Javascript

    $(".download").click(function (e) {
    
        e.preventDefault();
        var link = $(this);
        $('.loading').show();
    
        $.ajax({
            type: 'HEAD',
            url: link.attr('href'),
            complete: function () {
    
                $('.loading').hide();
                var ifr = $('<iframe />').attr('src', link.attr('href')).hide().appendTo(link)
                setTimeout(function () {ifr.remove();}, 5000);
            }
    
        });
    
    });
    
    0 讨论(0)
提交回复
热议问题