I am using the following code to covert a canvas image to blob.
In order to convert the blob to a file/filelist object, I need to pass that filelist to file handler.
Mycode:
var canvas1 = document.getElementById("preview");
var theImage = document.getElementById("blahProfile");
theImage.src = canvas1.toDataURL();
var blob = dataURItoBlob(theImage.src);
Is there any way to convert that blob to a file object?
I am using the following code to covert a canvas image to blob.
In order to convert the blob to a file/filelist object, I need to pass that filelist to file handler.
Mycode:
var canvas1 = document.getElementById("preview");
var theImage = document.getElementById("blahProfile");
theImage.src = canvas1.toDataURL();
var blob = dataURItoBlob(theImage.src);
Is there any way to convert that blob to a file object?
Share Improve this question edited Nov 12, 2014 at 7:28 gion_13 41.5k10 gold badges98 silver badges111 bronze badges asked May 29, 2014 at 6:20 madan Vmadan V 8443 gold badges19 silver badges40 bronze badges2 Answers
Reset to default 5File
objects contain more information than Blob
objects, with properties like lastModifiedDate
, and fileName
. It doesn't make sense for your image data to have either of those properties, because it's not a file.
I assume you FileList
handler users a FileReader
to read File
objects. However, the FileReader
methods can process Blob
objects as well (because File
is a subclass of Blob
). Thus, you can either:
extract your
FileReader
code into a separate function that accepts aBlob
orFile
(and possibly a resolution callback function) amd call that function when handling each of yourFileList
items and when processing yourBlob
of image dataif your
FileList
handler only accesses list items by index (e.g.,myFileList[i]
) then you could fake aFileList
simply by using an array ofBlob
s. For example, this function works with either a realFileList
or array ofBlob
s:function processFileList(list) { var reader = new FileReader(); reader.readAsText(list[0]); reader.addEventListener("loadend", function() { console.log(reader.result); }); }
// const file = new File([blob], imageFile.name,{
// type:imageFile.type,
// lastModified: new Date().getTime()
// }, 'utf-8');
const newFiles = [File,File...]
const dataTransfer = new DataTransfer();
newFiles.forEach(file => {
dataTransfer.items.add(file)
});
// dataTransfer.files => FileList
// add the FileList to <input> of typr file
input.files = dataTransfer.files;