Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting image object to File object, javascript

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

  • convert image to file
  • upload file to blob storage using angular-azure-blob-upload

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?

like image 451
HongKun Yoo Avatar asked Jan 20 '15 10:01

HongKun Yoo


1 Answers

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

like image 60
cuixiping Avatar answered Sep 23 '22 10:09

cuixiping