How to Get a File() or Blob() from an Url in JavaScript

How to get a File() or Blob() from an URL in javascript?

Try using the fetch API. You can use it like so:

fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
// Here's where you get access to the blob
// And you can use it for whatever you want
// Like calling ref().put(blob)

// Here, I use it to make an image appear on the page
let objectURL = URL.createObjectURL(blob);
let myImage = new Image();
myImage.src = objectURL;
document.getElementById('myImg').appendChild(myImage)
});
<div id="myImg"></div>

Get Blob object back from blob URL created with URL.createObjectURL

See this answer of mine for a way to retrieve the Blob from a blob: URI (you need to run the script there before the Blob is created by the page). Fetching only creates a copy.

The blob: URL is linked to the remote server in that it shares the same origin. So yes, the Blob (binary data) is on your computer, but the URL is only accessible to scripts running from the same origin than the one it was generated from.

And yes, the Blob does contain all the video data, but the string you have is a blob: URL, which is only a pointer to that Blob, itself stored in the browser's memory.

Convert URL to File or Blob for FileReader.readAsDataURL

This information is outdated as of now, but cannot be deleted.

  1. You can create File instances just by specifying a path when your code is chrome-privileged:

    new File("/path/to/file");

    File is a sub-class of Blob, so all File instances are also valid Blobs.
    Please note that this requires a platform path, and not a file URL.

  2. Yes, FileReader is available to addons.

File and FileReader are available in all windows. If you want to use them in a non-window scope (like bootstrap.js or a code module), you may use nsIDOMFile/nsIDOMFileReader.

How can i read data from blob url?

As spec says, readAsDataURL accept Blob only (which is File inheritor) as a param.

So you need to use original blob file reference (if you have it) or convert URL into file instance.

To convert image URL into the file itself, you can do the following.

async function convertToFile(url){
let response = await fetch(url);
let blob = await response.blob();

return new File([blob], 'put_the_name.jpg', {
type: 'image/jpeg'
});
}

// usage
async function main() {
const url = document.getElementById("test").value; // get file URL somehow
const file = await convertToFile(url); // usage of function above

const reader = new FileReader();
reader.readAsDataURL(file);
...
}

Or if you have an input in your markup for uploading files (which is popular use case), you can get file reference directly.

var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();

if (file) {
reader.readAsDataURL(file);
}


Related Topics



Leave a reply



Submit