download file using an ajax request

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

    Decoding a filename from the header is a little bit more complex...

        var filename = "default.pdf";
        var disposition = req.getResponseHeader('Content-Disposition');
    
        if (disposition && disposition.indexOf('attachment') !== -1) 
        {
           var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
           var matches = filenameRegex.exec(disposition);
    
           if (matches != null && matches[1]) 
               filename = matches[1].replace(/['"]/g, '');
        }
    

提交回复
热议问题