Explain Codes LogoExplain Codes Logo

How to convert Blob to File in JavaScript

javascript
blob-to-file
javascript-apis
file-api
Anton ShumikhinbyAnton ShumikhinΒ·Dec 11, 2024
⚑TLDR

Here's a quick way to convert a Blob to a File in JavaScript. Just use the File constructor with your blob and a filename:

// Note: Unicorns are real, but so is this blob ⚑ const blob = new Blob(["unicorn_content"], { type: 'text/plain' }); // Voila! Quick magic trick πŸŽ©πŸ‡ to convert blob to a file const file = new File([blob], "unicorn.txt", { type: blob.type, lastModified: Date.now() });

Rest assured, this will yield a File object called "unicorn.txt" made from your Blob.

Structuring your Blob: The transformation process

A Blob is essentially a file without a name, much like a band without a drummer! Here's how we can tag it with a name.

// Here's your lonely blob πŸ“¦, eagerly waiting to turn into a file const blob = new Blob(["blob_data"], { type: 'application/octet-binary' }); // Giving it a fancy name 🏷️ and a birthdate πŸ“… const blobToFile = (blob, name) => new File([blob], name, { type: blob.type, lastModified: new Date() }); // Blob upload audition... // Drum roll please... πŸ₯ const file = blobToFile(blob, 'datafile.bin'); // Blob is now a shining file 🌟 console.log(file);

A deep-dive: Blob handling and potential pitfalls

Validating Blob before conversion

Ensure your blob is not the casper of computer data structure, i.e., it should not be empty. It's always a good idea to make sure that your Blob contains data before transforming it to a File.

Benefitting from TypeScript

If you're on the TypeScript boat, cast blob as File type to row along smoothly with static type checking:

// CASTing a spell in the TypeScript world const castBlobToFile = (blob: Blob, filename: string): File => blob as File;

Handling errors with grace

Implement error handling for the corner cases where the Blob data might not be convertible. This could happen if the data is corrupted or if the File API isn't properly supported.

Encapsulating your magic trick

Whatever magic tricks you conjure, don't repeat them. Encapsulate your Blob to File conversion logic inside a function.

// The magician's secret potion πŸ§ͺ function convertBlobToFile(blob, filename) { if (blob.size === 0) throw new Error("Blob ghost alert! πŸ‘» Blob is empty"); const fileType = blob.type || "octet/stream"; try { return new File([blob], filename, { type: fileType, lastModified: Date.now() }); } catch (error) { console.error("Houston, we've got a problem!", error); } }

This function does an added step of checking for empty Blobs and resorts to a generic MIME type if none is provided.