download file using an ajax request

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

    @Joao Marcos solution works for me but I had to modify the code to make it work on IE, below if what the code looks like

           downloadFile(url,filename) {
            var that = this;
            const extension =  url.split('/').pop().split('?')[0].split('.').pop();
    
            var req = new XMLHttpRequest();
            req.open("GET", url, true);
            req.responseType = "blob";
            req.onload = function (event) {
                const fileName = `${filename}.${extension}`;
                const blob = req.response;
    
                if (window.navigator.msSaveBlob) { // IE
                    window.navigator.msSaveOrOpenBlob(blob, fileName);
                } 
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);                
                link.download = fileName;
                link.click();
                URL.revokeObjectURL(link.href);
    
            };
    
            req.send();
        },
    

提交回复
热议问题