How to convert Blob to File in JavaScript

Javascriptnode.jsFile UploadBlob

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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");

Solution 3 - Javascript

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"

Solution 4 - Javascript

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

Solution 5 - Javascript

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 })

Solution 6 - Javascript

My modern variant:

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

Solution 7 - Javascript

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

I used 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 the key the value it's not important.

Solution 8 - Javascript

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");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionskipView Question on Stackoverflow
Solution 1 - JavascriptJoshua P NixonView Answer on Stackoverflow
Solution 2 - JavascriptFiniteLooperView Answer on Stackoverflow
Solution 3 - JavascriptmiliView Answer on Stackoverflow
Solution 4 - JavascriptHossam EL-KashefView Answer on Stackoverflow
Solution 5 - JavascriptAlexandre DaubricourtView Answer on Stackoverflow
Solution 6 - JavascriptDAVID _View Answer on Stackoverflow
Solution 7 - JavascriptSajad SaderiView Answer on Stackoverflow
Solution 8 - JavascriptmylnzView Answer on Stackoverflow