3

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?

2 Answers 2

5

File 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 a Blob or File (and possibly a resolution callback function) amd call that function when handling each of your FileList items and when processing your Blob of image data

  • if your FileList handler only accesses list items by index (e.g., myFileList[i]) then you could fake a FileList simply by using an array of Blobs. For example, this function works with either a real FileList or array of Blobs:

    function processFileList(list) {
        var reader = new FileReader();
        reader.readAsText(list[0]);
        reader.addEventListener("loadend", function() {
            console.log(reader.result);
        });
    }
    
Sign up to request clarification or add additional context in comments.

3 Comments

can i add those two file properties to blob.
@madanV Sure, JavaScript allows you add new properties to anything, so you could make up a fake file name and add it as a fileNameproperty on the Blob. It will then have whatever fileName you made up and attached to it. A "natural" File object will have a fileName that reflects the name of the selected file (but in your case, the Blob is just data and doesn't have a filename because it's not from the user's filesystem).
how can i add name property to blob object.
1
        // 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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.