2

How can I convert a file (png/jpg/word/excel etc) to base64 format if I have url of the file (in the browser's sandboxed LocalFileSystem) which is already there in client system using javascript.

I had tried using creating canvas(image).
I also tried file control.
I don't want to use any control as we have url of the file in the sqllite db.

I tried

function UploadAttachmentfile() {
try {
      if(objAttachment.length >0)
      {
               var ctn = objAttachment.length;
                              for (var j = 0; j < ctn; j++) {
                              var row = objAttachment[j].IMGS; \\image
                                  var fname = row.split('\\').pop().split('/').pop();
                                  alert(fname);
                                  window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (fs) {
                                  alert('request file system');
                                      fs.root.getDirectory("Foldername", null, function (entry) {
                                      alert('ENTRY : '+entry);
                                          entry.getFile(fname, null, function (fileEntry) {
                                              fileEntry.file(gotFile, fail);
                                          }, fail);
                                      }, fail);
                                  }, fail);
                                  function gotFile(file) {
                                      readDataUrl(file);
                                  }

                                  function readDataUrl(file) {
                                      var reader = new FileReader();
                                      reader.onloadend = function (evt) {
                                          alert("Read as data URL");
                                          alert("target result :"+evt.target.result);
                                      };
                                      reader.readAsDataURL(file);
                                  }

                                  function fail(evt) {
                                  alert('fail');
                                      alert(evt.target.error.code);
                                  }


                              }

                               }

}
catch (err) {
        }
}

But it always alert fail only.

user3386468
  • 96
  • 1
  • 2
  • 13

1 Answers1

4
  • If you want to get the file on the user's computer WITHOUT the user selecting it (EVERY SESSION AGAIN), then, you can not do it (thank <enter deity here>). I highly reccomend to read this answer linked here for a complete and up-to-date explenation.

  • If however your user selects the file during his session via an file-input enabled element, then it is simple:
    Assuming you've got the url using createObjectURL() after the user selected the file(s), then you simply use the file-reader's readAsDataURL( fileObject || local URL ) method:

    fileReader.readAsDataURL( fileObject );
    

    That will encode it to base64.

EDIT:
turns out you are developing for mobile phone using Cordova (I've added that tag to your Question). However that's still based on the file-api and has the same .readAsDataURL() method: see documentation here. It contains simple examples and notes on different mobile platforms!
Also, it seems you are trying to get a file from the LocalFileSystem interface of the File System API (that gives you access to the browser's sandboxed file system). So the other answer I linked to doesn't apply (much).

The following example (modified from the documentation linked above) should get you started:

<!DOCTYPE html>
<html>
  <head>
    <title>FileReader Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // Cordova is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
    }

    function gotFS(fileSystem) {
        fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
    }

    function gotFileEntry(fileEntry) {
        fileEntry.file(gotFile, fail);
    }

    function gotFile(file){
        readDataUrl(file);
    }

    function readDataUrl(file) {
        var reader = new FileReader();
        reader.onloadend = function(evt) {
            console.log("Read as data URL");
            console.log(evt.target.result);
        };
        reader.readAsDataURL(file);
    }

    function fail(evt) {
        console.log(evt.target.error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Read File</p>
  </body>
</html>

From here on, you change the console.log(evt.target.result); part: instead of writing the base64 output to the console, you send that string back to the server (again using AJAX, etc.)

Done :)

Community
  • 1
  • 1
GitaarLAB
  • 14,536
  • 11
  • 60
  • 80
  • Dear @GitaarLAB, Thanks for your Response. i am not using any file control. i have url in the db. I need to select it and convert that to base64 and send to server. – user3386468 Oct 12 '14 at 08:41
  • Dear @GitaarLAB. i am working on a hybrid application with jquery mobile and cordova. user will take picture/upload a file(any type) and will save in a folder and url to that file will be stored in db. i am able to get that URL. the concern is i need to convert that file in URL to Base64 and send that to server using ajax. – user3386468 Oct 12 '14 at 09:03
  • Thanks @GitaarLAB, done but how can we upload from a list using loop? – user3386468 Oct 15 '14 at 10:22
  • Dear @GitaarLAB, Please help if you can find a solution for [related](http://stackoverflow.com/questions/26388689/how-to-upload-multiple-files-in-jquery-mobile-using-window-resolvelocalfilesyste) – user3386468 Oct 15 '14 at 17:41