0

I have this code to download an xml file, that is generated from a json. I do this with a function called jsonToSsXml(). That works, is all fine. But when I want to download, not every download works. I have no error messages, I put some console.logs to see if the blob is generated and it does

var download = function(content, filename, contentType) {
    if(!contentType) contentType = 'application/octet-stream';
    var a = document.getElementById('excel');
    var blob = new Blob([content], {'type':contentType});
    a.href = window.URL.createObjectURL(blob);
    console.log(a.href); //blob:http://mydomain/c72b5368-1fd1-48a1-9b32-858e8d3ab6b5
    a.download = filename;
    console.log(a.download);//formulario.xls
    //window.URL.revokeObjectURL(blob);
};
download(jsonToSsXml(campos), 'formulario.xls', 'application/vnd.ms-excel');

As I said, it works in some cases and others not. It can't be problem with my "content" value, it's a simple xml, they are all generated ok. I have the last line on the download function commented (URL.revokeObjectURL method), because I'm not sure how to use it and if it has something to do in this situation. Any tip?

edit: In random cases (but always with the same file) I got a 404 error, that the file is not found, but the blob url is generated always as console.log shows.

pmiranda
  • 7,602
  • 14
  • 72
  • 155

1 Answers1

0

I needed a delay:

setTimeout(function(){
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);  
}, 100);

Took the answer from this: Blob createObjectURL download not working in Firefox (but works when debugging)

Community
  • 1
  • 1
pmiranda
  • 7,602
  • 14
  • 72
  • 155