download file using an ajax request

后端 未结 12 2393
旧时难觅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:24

    To make the browser downloads a file you need to make the request like that:

     function downloadFile(urlToSend) {
         var req = new XMLHttpRequest();
         req.open("GET", urlToSend, true);
         req.responseType = "blob";
         req.onload = function (event) {
             var blob = req.response;
             var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
             var link=document.createElement('a');
             link.href=window.URL.createObjectURL(blob);
             link.download=fileName;
             link.click();
         };
    
         req.send();
     }
    

提交回复
热议问题