4

<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.

3

1 Answer 1

1

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)
;
Sign up to request clarification or add additional context in comments.

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.