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?
My modern variant:
You can use the File constructor:
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
This function converts a
Blob
into aFile
and it works great for me.Vanilla JavaScript
TypeScript (with proper typings)
Usage
Use
saveAs
on FileSaver.js github project.FileSaver.js
implements thesaveAs()
FileSaver interface in browsers that do not natively support it.Joshua P Nixon's answer is correct but I had to set last modified date also. so here is the code.
1534584790000 is an unix timestamp for "GMT: Saturday, August 18, 2018 9:33:10 AM"