JavaScript > JSON and Data Formats > Other Data Formats > Blob and File objects
Creating and Manipulating Blobs and Files in JavaScript
This example demonstrates how to create Blob and File objects in JavaScript, read their contents, and perform basic manipulations. Understanding Blobs and Files is crucial for handling binary data in web applications, especially when dealing with user uploads, media files, and data serialization.
Creating a Blob from a String
This snippet shows how to create a Blob object from a simple text string. The `Blob` constructor takes an array containing the data and an optional options object. Here, the options object specifies the `type` as 'text/plain', which indicates the MIME type of the data. The `console.log(blob)` will display the Blob object details in the console. Size reflects the size of the text data in bytes, and Type is the MIME type we specified. Blobs are immutable binary-like objects representing raw data.
// Create a Blob from a string
const text = 'Hello, Blob world!';
const blob = new Blob([text], { type: 'text/plain' });
// Log the blob
console.log(blob);
// Display the blob's properties
console.log('Blob size:', blob.size);
console.log('Blob type:', blob.type);
Creating a File from a Blob
This snippet demonstrates creating a File object from a Blob. The `File` constructor accepts an array containing a Blob (or other File/Blob objects), a filename, and an optional options object. In this example, we create a Blob from a text string, then use that Blob to create a File named 'myFile.txt'. The `File` object inherits properties from the `Blob` object (size, type) and adds properties like `name` (filename) and `lastModified`.
// Create a File from a Blob
const text = 'This is file content.';
const blob = new Blob([text], { type: 'text/plain' });
const file = new File([blob], 'myFile.txt', { type: 'text/plain' });
// Log the file
console.log(file);
// Display the file's properties
console.log('File name:', file.name);
console.log('File size:', file.size);
console.log('File type:', file.type);
console.log('Last modified:', file.lastModified);
Reading Blob/File Contents as Text
This snippet shows how to read the contents of a Blob (or File) as text using the `FileReader` API. A `FileReader` is instantiated and its `onload` event handler is set. The `readAsText()` method initiates the reading process. When the reading is complete, the `onload` event is triggered, and the content of the Blob is available in `event.target.result`. This is a common pattern for processing user-uploaded files.
// Reading Blob contents as text using FileReader
const text = 'Some text data.';
const blob = new Blob([text], { type: 'text/plain' });
const reader = new FileReader();
reader.onload = function(event) {
console.log('File content:', event.target.result);
};
reader.readAsText(blob);
Reading Blob/File Contents as Data URL
This example demonstrates reading Blob content as a Data URL. The `readAsDataURL()` method of the `FileReader` encodes the Blob's data as a base64 string that can be used directly in HTML elements (like `` tags) or CSS. This is useful for embedding small files directly into your web page without making separate requests.
// Reading Blob contents as Data URL using FileReader
const text = 'Data for URL.';
const blob = new Blob([text], { type: 'text/plain' });
const reader = new FileReader();
reader.onload = function(event) {
console.log('Data URL:', event.target.result);
// You can use the Data URL in an <img> tag, for example:
// document.getElementById('myImage').src = event.target.result;
};
reader.readAsDataURL(blob);
Concepts Behind Blobs and Files
Blobs represent raw, immutable data. They are used for handling binary data, such as images, audio, and video. Files are a specific type of Blob that have a filename and last modified date. Blobs and Files are fundamental for interacting with user-uploaded data and working with local files in web applications. They abstract away the complexities of dealing with binary data directly.
Real-Life Use Case
A common use case is handling image uploads. When a user uploads an image, the browser provides a `File` object. You can then use a `FileReader` to read the image data as a Data URL and display a preview before uploading it to the server. Alternatively, you might use the `File` object to upload the binary data directly to the server using `XMLHttpRequest` or `fetch`.
Best Practices
Interview Tip
Be prepared to explain the difference between Blobs and Files, and how to read their contents using the `FileReader` API. Also, understand how to handle errors during file processing. Mentioning security considerations (e.g., sanitizing filenames) demonstrates a deeper understanding.
When to Use Them
Use Blobs when you need to represent raw, binary data that doesn't necessarily correspond to a file. Use Files when you're dealing with data that has a filename and other file-related properties. They are essential when processing file uploads, manipulating media files, or serializing complex data structures.
Memory Footprint
Blobs and Files can consume significant memory, especially for large files. Reading the entire contents of a file into memory can be resource-intensive. Consider using techniques like streaming or chunking to process large files more efficiently. Also, remember to release resources (e.g., by setting `FileReader` references to `null`) when they are no longer needed to avoid memory leaks.
Alternatives
For simple text data, you might consider using strings directly. However, Blobs and Files provide more flexibility for handling binary data and interacting with file system APIs. Libraries like `FileSaver.js` can simplify the process of saving Blobs and Files to the user's local file system.
Pros
Cons
FAQ
-
What is the main difference between a Blob and a File?
A File is a specific type of Blob. A File has a filename and last modified date, while a Blob represents raw binary data without any associated metadata. -
How can I upload a Blob to a server?
You can upload a Blob using `XMLHttpRequest` or the `fetch` API. Set the `Content-Type` header appropriately to indicate the MIME type of the data. The Blob can be directly sent as the request body. -
Can I create a Blob from an ArrayBuffer?
Yes, you can create a Blob from an ArrayBuffer, TypedArray (e.g., Uint8Array), or DataView. The Blob constructor accepts an array of these types.