download file using an ajax request

后端 未结 12 2354
旧时难觅i
旧时难觅i 2020-11-21 23:46

I want to send an \"ajax download request\" when I click on a button, so I tried in this way:

javascript:

var xhr = new XMLHttpRequest();
xhr.open(\         


        
12条回答
  •  迷失自我
    2020-11-22 00:32

    This solution is not very different from those above, but for me it works very well and i think it's clean.

    I suggest to base64 encode the file server side (base64_encode(), if you are using PHP) and send the base64 encoded data to the client

    On the client you do this:

     let blob = this.dataURItoBlob(THE_MIME_TYPE + "," + response.file);
     let uri = URL.createObjectURL(blob);
     let link = document.createElement("a");
     link.download = THE_FILE_NAME,
     link.href = uri;
     document.body.appendChild(link);
     link.click();
     document.body.removeChild(link);
    

    This code puts the encoded data in a link and simulates a click on the link, then it removes it.

提交回复
热议问题