最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

cordova - Convert any type of file into Base64 using javascript if we have URL of the file reside inside client system - Stack O

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Oct 13, 2014 at 8:03 user3386468 asked Oct 12, 2014 at 6:54 user3386468user3386468 1061 gold badge2 silver badges15 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4
  • If you want to get the file on the user's puter WITHOUT the user selecting it (EVERY SESSION AGAIN), then, you can not do it (thank <enter deity here>). I highly recend to read this answer linked here for a plete 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 :)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论