如何使用Javascript将Image对象转换为File对象

4

<img id="uImage" src="C:\Image.jpg" >
<input type="file" name="file" id="ufile" />

我该如何将图片转换为文件对象?或者我该如何使用JavaScript创建/声明新的File()并手动插入它。

请查看此链接:http://www.javascripture.com/FileReader。 - Rana Ahmer Yasin
有各种类型的文件使用案例。 - Rana Ahmer Yasin
这个链接将教你高级技巧 https://scotch.io/tutorials/use-the-html5-file-api-to-work-with-files-locally-in-the-browser - Rana Ahmer Yasin
1个回答

1
通常情况下,无法向<input type=file ...>元素添加文件。

但是您可以通过FormData和XMLHttpRequest或fetch将您的File对象上传到服务器。

//load src and convert to a File instance object  
//work for any type of src, not only image src.  
//return a promise that resolves with a File instance  

    function srcToFile(src, fileName, mimeType){
        return (fetch(src)
            .then(function(res){return res.arrayBuffer();})
            .then(function(buf){return new File([buf], fileName, {type:mimeType});})
        );
    }

使用示例:(适用于Chrome和Firefox)
将src转换为File并上传到服务器

srcToFile('/images/logo.png', 'logo.png', 'image/png')
.then(function(file){
    var fd = new FormData();
    fd.append('file1', file);
    return fetch('/upload.php', {method:'POST', body:fd});
})
.then(function(res){
    return res.text();
})
.then(console.log)
.catch(console.error)
;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接