Today I had an interesting challenge. I had to download a file in javascript. Why through javascript and not through a link or a form post?
- I had to set a custom accept header to get the file into a specific format (in my case in excel format)
- I had to pass too many parameters to fit in a querystring.
So here’s the code i ended up using:
export function downloadFile(url: string, message: any, method: string, contentType ? : string, acceptContentType ? : string) { var xhr = new XMLHttpRequest(); xhr.open(method, url); if (acceptContentType) { xhr.setRequestHeader('Accept', acceptContentType); } if (contentType) { xhr.setRequestHeader('content-type', contentType); } xhr.responseType = 'blob'; xhr.onload = function() { if (this.status >= 400) { alert('error') } else { if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(xhr.response, 'afile.xlsx'); } else { var objectUrl = URL.createObjectURL(xhr.response); window.location.href = objectUrl; } } }; xhr.send(message); }
I tried to do this via jquery.ajax but I couldn’t get it to work. So then I switched to using xmlhttprequest. This worked fine, though saving a file in javascript works differently in chrome / explorer.