Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blob createObjectURL download not working in Firefox (but works when debugging)

I have an odd problem, the function below is one I created based on what i found on the net about creating a Blob in the client on the fly with some binary data in (passed as an array) and being able to download that. This works brilliantly in Chrome, but doesn't do anything in Firefox - UNLESS I debug and step through the code. Yes, oddly, if I create a break point inside the function and step through it, the a.click() will bring up the download window!

function downloadFile(filename, data) {      var a = document.createElement('a');     a.style = "display: none";       var blob = new Blob(data, {type: "application/octet-stream"});     var url = window.URL.createObjectURL(blob);     a.href = url;     a.download = filename;     document.body.appendChild(a);     a.click();     document.body.removeChild(a);     window.URL.revokeObjectURL(url);     } 

Can anyone help me? This was tested using Firefox 38.0.5.

like image 567
Johncl Avatar asked Jun 07 '15 14:06

Johncl


People also ask

How does URL createObjectURL work?

The URL. createObjectURL() static method creates a string containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.

How do I open a Blob File in browser?

If you cannot open your BLOB file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a BLOB file directly in the browser: Just drag the file onto this browser window and drop it.

What does createObjectURL return?

Return value: A DOMString containing an object URL of that object.

Is createObjectURL Async URL?

createObjectURL is synchronous but it seems to complete almost instantaneously.


1 Answers

You're probably removing the resource too soon, try delaying it

    ...     a.click();     setTimeout(function(){         document.body.removeChild(a);         window.URL.revokeObjectURL(url);       }, 100);   } 
like image 118
Musa Avatar answered Sep 23 '22 22:09

Musa