Convert a Blob to a File using JavaScript

Sometimes you get a Blob object when instead you would like to have a File. For example, when you use blob() on a fetch response object. In this quick tutorial we’ll explore how to turn a Blob into a File.

Fetch

The script below converts a fetch response into a Blob.

fetch("./image.jpeg")
  .then((res) => res.blob())
  .then((myBlob) => {
    console.log(myBlob);
    // logs: Blob { size: 1024, type: "image/jpeg" }
  });

But what if we want a File?

The main difference between a Blob and a File is that the File has a name and lastModified property, it inherits all it’s other properties from Blob.

We can take two routes, either we add these two properties to the Blob to make it seem like a File. Or we create an actual File instance.

Making a Blob quack like a File

Let’s add the two properties to our Blob instance (the one from our fetch request above).

myBlob.name = "image.jpeg";
myBlob.lastModified = new Date();

Our Blob now seems like a File but it’s not a real File, we can easily check this:

console.log(myBlob instanceof File);
// logs: false

console.log(myBlob);
// logs: Blob { name: "image.jpeg", lastModified: ..., size: 1024, type: "image/jpeg" }

This might cause a problem if we use this with a third-party script which requires an actual File object.

Creating an actual File

This is the better approach, it’ll give us an actual File object.

const myFile = new File([myBlob], "image.jpeg");
console.log(myFile);
// logs: File { name: "image.jpeg", lastModified: ..., size: 1024, type: "image/jpeg" }

Now when we check the instance it’ll be a File.

console.log(myFile instanceof File);
// logs: true

But, as it inherits from Blob it’ll also be a Blob.

console.log(myFile instanceof Blob);
// logs: true

Why did we discuss the quack likes a duck method? Because IE11 doesn’t support the File constructor so if you still need to support Internet Explorer, that’s the way to go.

I use Twitter to share new webdevelopment tips and tricks, so Follow me there if you found this interesting and want to learn more.

Rik Schennink

Indie Product Developer

to pqina.nl