Convert Blob to File

How to convert Blob to File in 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");

How to create File object from Blob?

The File constructor (as well as the Blob constructor) takes an array of parts. A part doesn't have to be a DOMString. It can also be a Blob, File, or a typed array. You can easily build a File out of a Blob like this:

new File([blob], "filename")

Convert an image from file upload to blob to post to database VueJS

You need to take the values.image, console.log the response from it so see how the data is structured. There should be a string value in there that you may need to split at . so that you can take the MIME type of the file that you have uploaded as you need this to create the blob.

The structure of a Blob is like so.

new Blob(blobParts, options);

/**
* blobParts is an array of Blob/BufferSource/String values.
* options: option object:
* type - Blob type, usually MIME-type e.g image/png
* endings - whether to transform end-of-line to make the Blob corrospond to current OS newlines.
*/

You should also be able to turn this into a Blob by calling the .blob() function on the file that has been uploaded.

A dummy is as so:

// your file name in the second param should be constructed of the string that you have logged and split earlier.
var fileToUpload = new File([Blob], 'some_file_name.jpg', {
type: "image/jpg", // this should be from your string split of the filename to check the file upload type.
lastModified: new Date(),
});

form.append("image", fileToUpload);



Related Topics



Leave a reply



Submit