I want to convert "image object" to "File object" using HTML5 in client side to upload the File to the azure blob storage.
Since I'm using AngularJs, my plan is to
I have found lots of examples that convert File object to image using FileReader, but I can't find the opposite example.
I heard it is impossible to write files to local file system with client javascript, but I don't need to store the File, I just need the file object reference to upload the file.
Is there any way to solve this problem?
You can use fetch and FormData to convert and upload.
//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 php
srcToFile('/images/logo.png', 'new.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)
;
For your case, just replace '/images/logo.png'
with imageObject.src
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With