I wondered about getting previews and initial information about the file before downloading it. Almost everything I read about this is based on using the FileReader () object in JavaScript.
However, in order to display the preview, you must first get the file object from input and transfer it to FileReader, and FileReader in turn waits for the file to be downloaded (if I understood correctly, to a temporary folder) and therefore if you transfer a large enough file to an object, then preview will be created for very long. Therefore, I found a solution using the URL.createObjectURL to which the file object is also transmitted and which immediately gives a link to the file as a "blob: link", and you can immediately get a preview of a video or image of any size.
Actually, why almost always use FileReader, if it does not allow you to make a preview immediately for large files?

    1 answer 1

    Comparison:

    1) lead time

    • createObjectURL runs synchronously (very quickly)
    • FileReader.readAsDataURL asynchronous, requires callback (really not as fast)

    2) memory usage

    • createObjectURL returns the current site's blob url ( blob:http://examle.com/f91de9c4-b515-4615-9895-15089b364b7f ), and stores the object in memory until the unload event (i.e. closing the document) or until revokeObjectURL is revokeObjectURL
    • FileReader.readAsDataURL returns base64 which contains many characters and uses more memory than a blob url, but is removed from memory if not used (thanks to the garbage collector).

    3) support

    • createObjectURL from IE 10 and up and in all modern browsers
    • FileReader.readAsDataURL from IE 10 and higher and in all modern browsers

    If you need to make a preview for a picture, then personally I prefer using blob url's (via createObjectURL ), this is more efficient and faster, but remember that if you use many objects, be sure to use revokeObjectURL (to free up memory). As for FileReader, it works well if you need to get a base64 string, which can be transferred to api, for example, and save the picture itself, you can’t do this with a blob, but if you just need to preview the picture, createObjectURL more efficient! .

    For example, you can call the URL.revokeObjectURL inside the onload image handler and after that the image object will contain the image data without loss.

    Example of use:

    FileReader

     input.onchange = function (event) { var file = event.target.files[0] var reader = new FileReader() reader.onloadend = function () { console.log('RESULT', reader.result) } reader.readAsDataURL(file) } 

    URL.createObjectURL ()

     input.onchange = function (event) { var file = event.target.files[0] var url = URL.createObjectURL(file) console.log('RESULT', url ) }