简体   繁体   中英

How to read an image file from sdcard and get it to the src of a img tag in phonegap?

I am trying to read an image from the sdcard which is not taken by the phone camera and get the image src to show on my app. I tried many solutions to this and got many updates. But still it's not working. Here is my code:

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess);
}
function onFileSystemSuccess(fileSystem){
    fileSystem.root.getFile("test.jpg", {create: false, exclusive: false}, fileSuccess);
}

function fileSuccess(fileEntry){
    fileEntry.file(gotfile);
}

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

function readDataUrl(file){
    var reader = new FileReader();
    reader.onlaodend=function(evt){
        console.log(evt.target.result); 
        document.getElementById("img_test").src=evt.target.result;
    };
    reader.readAsDataURL(file);
}

and I am trying to get this src of img:

<div>
    <img id="img_test" src="">
</div>

Is there anything wrong with the filepath? I am new to phonegap. Please let me know what I am doing wrong here. Thank you...:)

Here is a working example this helps you :

<!DOCTYPE html>
<html>
  <head>
    <title>Pick Photo</title>

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

    document.addEventListener("deviceready",onDeviceReady,false);

    function onDeviceReady() {
       window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, onFail);
    }

     function onFail(message) {
      alert('Failed because: ' + message);
    }

    function gotFS(fileSystem) {
        fileSystem.root.getFile("1.jpg", {create: true}, 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);
           document.getElementById("smallImage").style.display='block'; 
           document.getElementById("smallImage").src = evt.target.result;   
        }; 
        reader.readAsDataURL(file);
    }

    function fail(evt) {
        console.log(evt.target.error.code);
    }
    </script>
  </head>
  <body>
    <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
    <img style="display:none;" id="largeImage" src="" />
  </body>
</html>

This will allow you to pick any specified image from sdcard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM