If, before sending a request, you set the XMLHttpRequest.responseType property to 'blob' , then when you receive a response, it will be presented as a blob. Then you can save the blob to a temporary file and go to it.
var postData = new FormData(); postData.append('cells', JSON.stringify(output)); var xhr = new XMLHttpRequest(); xhr.open('POST', '/export/', true); xhr.setRequestHeader('X-CSRFToken', csrftoken); xhr.responseType = 'blob'; xhr.onload = function (this, event) { var blob = this.response; var contentDispo = this.getResponseHeader('Content-Disposition');
And here is an example implementation of saveOrOpenBlob :
function saveOrOpenBlob(blob, fileName) { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) { fs.root.getFile(fileName, { create: true }, function (fileEntry) { fileEntry.createWriter(function (fileWriter) { fileWriter.addEventListener("writeend", function () { window.location = fileEntry.toURL(); }, false); fileWriter.write(blob, "_blank"); }, function () { }); }, function () { }); }, function () { }); }
If you do not need the browser to navigate to the file when it is available for viewing, then making a method that always saves directly to a file is much simpler:
function saveBlob(blob, fileName) { var a = document.createElement('a'); a.href = window.URL.createObjectURL(blob); a.download = fileName; a.dispatchEvent(new MouseEvent('click')); }
Steven doggart
source share