最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert Blob to File List in javascript - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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);
        });
    }
    
        // 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;
发布评论

评论列表(0)

  1. 暂无评论