Converting Blob to File in JavaScript: Methods and File Upload Implementation

Nov 18, 2025 · Programming · 12 views · 7.8

Keywords: JavaScript | Blob Conversion | File Upload | Data URL | Node.js

Abstract: This article provides an in-depth exploration of converting Blob objects to File objects in JavaScript, focusing on two primary methods: using the File constructor and property extension. With practical examples covering data URL conversion, Blob handling, and file upload scenarios, it offers complete code implementations and best practices for efficient file data processing between frontend and backend systems.

Fundamental Concepts of Blob and File Objects

In web development, Blob (Binary Large Object) objects represent immutable raw data chunks, commonly used for handling binary data. The File interface extends Blob, adding file system-related properties such as filename and last modified time. Understanding the relationship between these two is fundamental to data conversion.

Data URL to Blob Conversion Implementation

When handling scenarios like image uploads, converting data URLs to Blob objects is often necessary. Here's a complete conversion function implementation:

function dataURLToBlob(dataURL) {
    const BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) === -1) {
        const parts = dataURL.split(',');
        const contentType = parts[0].split(':')[1];
        const raw = decodeURIComponent(parts[1]);
        return new Blob([raw], {type: contentType});
    }
    const parts = dataURL.split(BASE64_MARKER);
    const contentType = parts[0].split(':')[1];
    const raw = window.atob(parts[1]);
    const rawLength = raw.length;
    const uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {type: contentType});
}

This function first detects whether the data URL contains a base64 marker, then handles both regular encoding and base64 encoding cases separately, ensuring proper data content parsing and corresponding Blob object creation.

Core Methods for Blob to File Conversion

Converting Blob to File objects primarily involves two methods, each with its applicable scenarios and considerations.

Method 1: Using the File Constructor

The File constructor is the W3C standard recommended approach, directly creating new File objects:

const myFile = new File([myBlob], "filename.png", {
    type: "image/png",
    lastModified: new Date().getTime()
});

This method creates genuine File objects that comply with web standards and are well-supported in modern browsers.

Method 2: Property Extension Approach

Another method involves adding necessary properties to Blob objects to simulate File objects:

function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

In TypeScript environments, type assertions can ensure type safety:

public blobToFile = (theBlob: Blob, fileName: string): File => {
    const b: any = theBlob;
    b.lastModifiedDate = new Date();
    b.name = fileName;
    return theBlob as File;
}

This approach leverages the compatibility between Blob and File, demonstrating stable performance in practical applications.

Complete File Upload Workflow Implementation

Combining data URL conversion and Blob to File conversion enables a complete file upload workflow:

// Create Blob from data URL
const imageBlob = dataURLToBlob(imageDataURL);

// Convert Blob to File
const imageFile = blobToFile(imageBlob, "uploaded-image.png");

// Create FormData and prepare for upload
const formData = new FormData();
formData.append("image", imageFile);

// Upload using fetch API
fetch("/upload", {
    method: "POST",
    body: formData
})
.then(response => response.json())
.then(data => console.log("Upload successful:", data))
.catch(error => console.error("Upload failed:", error));

Technical Details and Best Practices

In actual development, several key points require attention:

Data Type Handling: Ensure proper handling of different MIME types, such as image/png, image/jpeg for images, which is crucial for subsequent file processing and display.

Browser Compatibility: The File constructor is well-supported in newer browsers, but older versions may require the property extension method as a fallback.

Memory Management: When handling large files, ensure timely release of Blob URLs to prevent memory leaks:

const blobUrl = URL.createObjectURL(blob);
// Release after use
URL.revokeObjectURL(blobUrl);

Error Handling: Add appropriate error handling mechanisms during conversion to ensure graceful exception handling when data formats are incorrect.

Performance Optimization Recommendations

For large file processing, consider using chunked uploads and streaming:

// Use Blob.slice() for chunk processing
const chunkSize = 1024 * 1024; // 1MB
let offset = 0;

while (offset < blob.size) {
    const chunk = blob.slice(offset, offset + chunkSize);
    // Upload chunk
    uploadChunk(chunk, offset);
    offset += chunkSize;
}

This approach effectively handles large files, prevents memory overflow issues, and supports resumable upload functionality.

Extended Practical Application Scenarios

Beyond basic file uploads, Blob to File conversion technology finds applications in various scenarios:

Image Editing Applications: Convert Canvas editing results to File objects for saving or sharing.

Document Processing: Handle preview and download functionality for PDF, Word, and other documents.

Multimedia Processing: Audio and video file editing and conversion processing.

By deeply understanding Blob and File conversion mechanisms, developers can build more powerful and flexible file processing capabilities, enhancing the user experience of web applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.