Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileReader vs. window.URL.createObjectURL

I'm building a mobile website and I'd like to use the Camera API to take photos. The images should be displayed on the website and uploaded to a server. According to the introduction to the Camera API on MDN the images can be accessed and displayed on the website using FileReader or window.URL.createObjectURL. I tested these possible solutions successfully with an iPad (Safari and Chrome) and an Android tablet (Chrome and Firefox).

What is the difference between FileReader and window.URL.createObjectURL? I think window.URL.createObjectURL is newer but not a standard yet. Is there a difference in the performance?

like image 837
nightlyop Avatar asked Jul 31 '15 08:07

nightlyop


People also ask

What is window URL createObjectURL?

createObjectURL() 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.

Is createObjectURL Async URL?

createObjectURL is synchronous but it seems to complete almost instantaneously. Also note that calling URL. revokeObjectURL in the image's onload handler breaks "Open image in New Tab" in the image's context menu.

Is createObjectURL deprecated?

The URL. createObjectURL() method has been removed from the MediaStream interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.

What does URL createObjectURL return?

createObjectURL is a static method provided by the URL Web API. Returns a DOMString containing a unique blob URL, that is a URL with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser.


1 Answers

There is difference.

  1. time
  • createObjectURL is synchronously executed (immediately)
  • FileReader.readAsDataURL is asynchronously executed (after some time)
  1. memory usage
  • createObjectURL returns url with hash, and store object in memory until document triggers unload event (e.g. document close) or execute revokeObjectURL
  • FileReader.readAsDataURL returns base64 that contains many characters, and use more memory than blob url, but removes from memory when you don't use it (by garbage collector)
  1. support
  • createObjectURL from IE 10 and all modern browsers
  • FileReader.readAsDataURL from IE 10 and all modern browsers

For me, is better to use blob url's (via createObjectURL), it is more efficient and faster, but if you use many object urls, you need to release these urls by revokeObjectURL (to free memory).

For example, you can call URL.revokeObjectURL inside an Image onload handler and the Image object will keep the image data, without losing it, Nahuel Greco (c).

like image 151
Alex Nikulin Avatar answered Sep 18 '22 05:09

Alex Nikulin