[javascript] How to convert Blob to File in JavaScript

I need to upload an image to NodeJS server to some directory. I am using connect-busboy node module for that.

I had the dataURL of the image that I converted to blob using the following code:

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

I need a way to convert the blob to a file to upload the image.

Could somebody help me with it?

This question is related to javascript node.js file-upload blob

The answer is


This function converts a Blob into a File and it works great for me.

Vanilla JavaScript

function blobToFile(theBlob, fileName){
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

TypeScript (with proper typings)

public blobToFile = (theBlob: Blob, fileName:string): File => {
    var b: any = theBlob;
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    b.lastModifiedDate = new Date();
    b.name = fileName;

    //Cast to a File() type
    return <File>theBlob;
}

Usage

var myBlob = new Blob();

//do stuff here to give the blob some data...

var myFile = blobToFile(myBlob, "my-image.png");

I have used FileSaver.js to save the blob as file.

This is the repo : https://github.com/eligrey/FileSaver.js/

Usage:

import { saveAs } from 'file-saver';

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

saveAs("https://httpbin.org/image", "image.jpg");

Joshua P Nixon's answer is correct but I had to set last modified date also. so here is the code.

var file = new File([blob], "file_name", {lastModified: 1534584790000});

1534584790000 is an unix timestamp for "GMT: Saturday, August 18, 2018 9:33:10 AM"


You can use the File constructor:

var file = new File([myBlob], "name");

As per the w3 specification this will append the bytes that the blob contains to the bytes for the new File object, and create the file with the specified name http://www.w3.org/TR/FileAPI/#dfn-file


Use saveAs on FileSaver.js github project.

FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it.


My modern variant:

function blob2file(blobData) {
  const fd = new FormData();
  fd.set('a', blobData);
  return fd.get('a');
}

For me to work I had to explicitly provide the type although it is contained in the blob by doing so:

const file = new File([blob], 'untitled', { type: blob.type })

This problem was bugg me for hours. I was using Nextjs and trying to convert canvas to an image file.

I just use the other guy's solution but the created file was empty.

So if this is your problem you should mention the size property in the file object.

new File([Blob], `my_image${new Date()}.jpeg`, {
  type: "image/jpeg",
  lastModified: new Date(),
  size: 2,
});

just add it, the value it's not important.


Typescript

public blobToFile = (theBlob: Blob, fileName:string): File => {       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}

Javascript

function blobToFile(theBlob, fileName){       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}

Output

screenshot

File {name: "fileName", lastModified: 1597081051454, lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 601887, …}
lastModified: 1597081051454
lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time) {}
name: "fileName"
size: 601887
type: "image/png"
webkitRelativePath: ""
__proto__: File

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to blob

Angular: How to download a file from HttpClient? How do we download a blob url video How to convert Blob to File in JavaScript Saving binary data as file using JavaScript from a browser Inserting Image Into BLOB Oracle 10g How to Display blob (.pdf) in an AngularJS app Difference between CLOB and BLOB from DB2 and Oracle Perspective? JavaScript blob filename without link How to convert Blob to String and String to Blob in java How to go from Blob to ArrayBuffer