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:
JavaScript
x
19
19
1
dataURLToBlob: function(dataURL) {
2
var BASE64_MARKER = ';base64,';
3
if (dataURL.indexOf(BASE64_MARKER) == -1) {
4
var parts = dataURL.split(',');
5
var contentType = parts[0].split(':')[1];
6
var raw = decodeURIComponent(parts[1]);
7
return new Blob([raw], {type: contentType});
8
}
9
var parts = dataURL.split(BASE64_MARKER);
10
var contentType = parts[0].split(':')[1];
11
var raw = window.atob(parts[1]);
12
var rawLength = raw.length;
13
var uInt8Array = new Uint8Array(rawLength);
14
for (var i = 0; i < rawLength; ++i) {
15
uInt8Array[i] = raw.charCodeAt(i);
16
}
17
return new Blob([uInt8Array], {type: contentType});
18
}
19
I need a way to convert the blob to a file to upload the image.
Could somebody help me with it?
Advertisement
Answer
This function converts a Blob
into a File
and it works great for me.
Vanilla JavaScript
JavaScript
1
7
1
function blobToFile(theBlob, fileName){
2
//A Blob() is almost a File() - it's just missing the two properties below which we will add
3
theBlob.lastModifiedDate = new Date();
4
theBlob.name = fileName;
5
return theBlob;
6
}
7
TypeScript (with proper typings)
JavaScript
1
10
10
1
public blobToFile = (theBlob: Blob, fileName:string): File => {
2
var b: any = theBlob;
3
//A Blob() is almost a File() - it's just missing the two properties below which we will add
4
b.lastModifiedDate = new Date();
5
b.name = fileName;
6
7
//Cast to a File() type
8
return <File>theBlob;
9
}
10
Usage
JavaScript
1
6
1
var myBlob = new Blob();
2
3
//do stuff here to give the blob some data...
4
5
var myFile = blobToFile(myBlob, "my-image.png");
6