How to download file from server using jQuery AJAX and Spring MVC 3

前端 未结 3 533
说谎
说谎 2020-12-01 02:43

I want to implement downloading (with AJAX) of uploaded file from server. On the server side I wrote the code

@RequestMapping(value = \"/getInvoice/approvalI         


        
相关标签:
3条回答
  • 2020-12-01 02:55

    Two options are usually used but neither involves AJAX. And jQuery won't be a great help either.

    Option 1: IFrame

    Place an invisible IFrame into your page:

    <iframe id="downloadFrame" style="display:none"></iframe>
    

    When the download should start (you didn't mention how it is triggered), use Javascript (and possibly jQuery) to set the URL for the IFrame, which is something like /getInvoice/approvalId/123 in your case:

    var iframe = document.getElementById("downloadFrame");
    iframe .src = "/getInvoice/approvalId/123";
    

    Setting the IFrame URL should trigger the browser to present the download dialog.

    Option 2: Navigate to the download URL

    The second option is even simpler. Just navigate to the download URL. Once the browser figures out it's a MIME type that cannot be displayed, it will present a download dialog.

    So when the download is triggered, execute the following JavaScript code:

    window.location.href = "/getInvoice/approvalId/123";
    

    Note

    I'm not sure if all browser will reliably present a download dialog with PDF files. Some browsers might try to display it within the browser itself. The Content-Disposition HTTP header is helpful but no guarantee.

    0 讨论(0)
  • 2020-12-01 03:04

    jQuery-ized answer by Codo:

       $('#downloadFrame').remove(); // This shouldn't fail if frame doesn't exist
       $('body').append('<iframe id="downloadFrame" style="display:none"></iframe>');
       $('#downloadFrame').attr('src','/downloadUrlGoesHere');
    
    0 讨论(0)
  • 2020-12-01 03:05

    Maybe a better strategy would be to use jQuery to build a new <A> link on the page that'll reference this same URL, and insert this new element at a appropriate place in the DOM. That being done, maybe jQuery can even then click it for the user, initiating the download.

    0 讨论(0)
提交回复
热议问题