How do I get browser to prompt user to save a file dynamically generated by server?

前端 未结 1 1996
旧时难觅i
旧时难觅i 2021-01-12 19:01

Clients submit post requests using jquery ajax as illustrated below:

$.ajax({
    url: \"/xxx?request1\", 
    data: theParams,
    type: \'post\',
    error         


        
相关标签:
1条回答
  • 2021-01-12 19:25

    Content-Disposition: attachment is the right header, but the browser only obeys it when loading the file directly. Using AJAX (even through jQuery) will not work.

    There is a way to do this. Read the full explanation in this answer, but basically you just have to write that in your success function:

    window.location = "data:application/octet-stream," + encodeURIComponent(theResult);
    

    Edit: FileSaver.js provides a wrapper improving browser compatibility and adding support for filenames for compatible browsers:

    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    saveAs(blob, "hello world.txt");
    
    0 讨论(0)
提交回复
热议问题