Randz Rover
Randz Rover

Reputation: 45

How to convert Image object to File Object using Javascript

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

How can I convert Image to File Object? Or how Can I create/declare new File() and insert it manually using javascript.

Upvotes: 4

Views: 3419

Answers (1)

cuixiping
cuixiping

Reputation: 25449

Commonly, it's impossible to add file to the <input type=file ...> element.

But you can upload your File object to server by FormData and XMLHttpRequest or fetch.

//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});})
        );
    }

Usage example: (works in Chrome and Firefox)
Convert src to File and upload to server

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)
;

Upvotes: 1

Related Questions