使用window.requestFileSystem()时,Phonegap / Cordova返回相同的图像

时间:2016-01-22 02:06:40

标签: cordova

我有一个奇怪的问题..

我需要从iOS模拟器手机库中获取几(4)张图片,然后更新4张图片中每张图片的src以显示它们。当不使用window.requestFileSystem()时,我可以把它们搞定,但因为它们存储在tmp中是不好的,因为它们在应用程序重新加载时会丢失,我希望它们能够持久存在(我将路径保存在localstorage中以便我可以如果用户在获得用户时离线,则稍后上传它们。

所以我开始使用文件系统来保存文件,但是当使用window.requestFileSystem()时,无论我选择什么图像,获取每个图像都会返回我选择的第一个图像。看起来navigator.camera.getPicture每次使用文件系统时都会返回相同的照片。

我想知道是否有人知道我做错了什么。这是我的整个JS。

// -----------------------------
// INIT
// -----------------------------
var networkState;
var pictureSource;
var destinationType;
var storage = window.localStorage;

console.log(storage);

// Listeners for online or offline status
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);


// When Device APIs are available
function onDeviceReady()
{
    //localStorage.clear();

    console.log("onDeviceReady");

    pictureSource = navigator.camera.PictureSourceType;
    destinationType = navigator.camera.DestinationType;

    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, FileIO.gotFS, FileIO.errorHandler);

    networkState = checkConnection();
    if(networkState == 'online')
    {
        sendLocalStorage();
    } 
}

// -----------------------------
// File System
// -----------------------------

// set some globals
var gImageURI = '';
var gFileSystem = {};

var FileIO = {

    // sets the filesystem to the global var gFileSystem
    gotFS : function(fileSystem) {
        gFileSystem = fileSystem;
    },

    // pickup the URI from the Camera edit and assign it to the global var gImageURI
    // create a filesystem object called a 'file entry' based on the image URI
    // pass that file entry over to gotImageURI()
    updateCameraImages : function(imageURI) {
        console.log(imageURI);
          gImageURI = imageURI;
          window.resolveLocalFileSystemURL(imageURI, FileIO.gotImageURI, FileIO.errorHandler);
       },

    // pickup the file entry, rename it, and move the file to the app's root directory.
    // on success run the movedImageSuccess() method
    gotImageURI : function(fileEntry) {

        var newName = fileEntry.name;
        fileEntry.moveTo(gFileSystem.root, newName, FileIO.movedImageSuccess, FileIO.errorHandler);
    },

    // send the full URI of the moved image to the updateImageSrc() method which does some DOM manipulation
    movedImageSuccess : function(fileEntry) {
        updateImageSrc(fileEntry.nativeURL);
        console.log("Image1URL: "+fileEntry.nativeURL);
    },

    // get a new file entry for the moved image when the user hits the delete button
    // pass the file entry to removeFile()
    removeDeletedImage : function(imageURI){
        window.resolveLocalFileSystemURL(imageURI, FileIO.removeFile, FileIO.errorHandler);
    },

    // delete the file
    removeFile : function(fileEntry){
        fileEntry.remove();
    },

    // simple error handler
    errorHandler : function(e) {
         var msg = '';
         switch (e.code) {
         case FileError.QUOTA_EXCEEDED_ERR:
                msg = 'QUOTA_EXCEEDED_ERR';
                break;
          case FileError.NOT_FOUND_ERR:
                msg = 'NOT_FOUND_ERR';
                break;
          case FileError.SECURITY_ERR:
                msg = 'SECURITY_ERR';
                break;
          case FileError.INVALID_MODIFICATION_ERR:
                msg = 'INVALID_MODIFICATION_ERR';
                break;
          case FileError.INVALID_STATE_ERR:
                msg = 'INVALID_STATE_ERR';
                break;
          default:
                msg = e.code;
          break;
        };
      console.log('Error: ' + msg);
    }
}



// -----------------------------
// Photo Functions
// -----------------------------


// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI, image)
{
    FileIO.updateCameraImages(imageURI);
}

function updateImageSrc(newImage)
{
    var image = "image2";
    console.log(newImage);

    // Get image handle
    var galleryImage = document.getElementById(image);

    // Unhide image elements
    galleryImage.style.display = 'block';

    // Show the captured photo
    // The inline CSS rules are used to resize the image
    galleryImage.src = newImage;

}


// A button will call this function
function capturePhoto(image)
{
    console.log("capturePhoto: "+image);

    // Take picture using device camera and retrieve image as base64-encoded string
    navigator.camera.getPicture(
        function(imageData)
        {
            onPhotoDataSuccess(imageData, image);
        },
        onFail,
        {
            quality: 70,
            targetWidth: 1000,
            //targetHeight: 600,
            destinationType: destinationType.FILE_URI,
            saveToPhotoAlbum: true
        }
    );
}



// -----------------------------
// Button Functions
// -----------------------------

// A button will call this function
function getPhoto(source, image)
{
    console.log("getPhoto: "+image);

    // Retrieve image file location from specified source
    navigator.camera.getPicture(
    function(imageData)
    {
        onPhotoURISuccess(imageData, image);
    },
    onFail,
    {
        quality: 70,
        targetWidth: 1000,
        //targetHeight: 600,
        destinationType: destinationType.FILE_URI,
        sourceType: source
    });
}



// -----------------------------
// Save Functions
// -----------------------------

// Save to Local Storage
function save()
{
    // Create a the ID number for this form submission

    // Create Date for formid
    var dt = new Date();
    var datetime = dt.getFullYear() + '-' + ("0" + (dt.getMonth() + 1)).slice(-2) + '-' + ("0" + dt.getDate()).slice(-2) + '-' + dt.getHours() + '-' + dt.getMinutes() + '-' + dt.getSeconds();

    // Create and Set formid
    var formid = datetime + '-' + convertToSlug($('#name').val());
    $('#formid').val(formid);

    // Get images
    var imageURI1 = document.getElementById('image1').getAttribute("src");
    var imageURI2 = document.getElementById('image2').getAttribute("src");
    var imageURI3 = document.getElementById('image3').getAttribute("src");
    var imageURI4 = document.getElementById('image4').getAttribute("src");

console.log("Image1URL: "+imageURI1);

    var images = {imageURI1:imageURI1, imageURI2:imageURI2, imageURI3:imageURI3, imageURI4:imageURI4};
    var imagesJSON = JSON.stringify(images);

    storage.setItem(formid, imagesJSON);


    // If online, send
    if(networkState == 'online')
    {
        sendLocalStorage();
    }

}






// Upload files to server
function sendLocalStorage()
{

    if(localStorage.length > 0)
    {
       for (var i = 0; i < localStorage.length; i++)
       {
           var formid = localStorage.key(i);
           var imagesJSON = storage.getItem(localStorage.key(i));
           var images = JSON.parse(imagesJSON);

            // Get images
           var imageURI1 = images.imageURI1;
           var imageURI2 = images.imageURI2;
           var imageURI3 = images.imageURI3;
           var imageURI4 = images.imageURI4;


           if(imageURI1!="")
           {
            $('#image1_process').show();
               fileTransfer(imageURI1, formid, "1");
            }

           if(imageURI2!="")
           {
                $('#image2_process').show();
               fileTransfer(imageURI2, formid, "2");
            }

           if(imageURI3!="")
           {
                $('#image3_process').show();
               fileTransfer(imageURI3, formid, "3");
            }

           if(imageURI4!="")
           {
                $('#image4_process').show();
               fileTransfer(imageURI4, formid, "4");
            }

        }
    }


}

function fileTransfer(imageURI, formid, imageNum)
{

    console.log("send: "+imageURI);

    name = formid + "-" + imageURI.substr(imageURI.lastIndexOf('/')+1);

    var options = new FileUploadOptions();
    options.fileKey="file";
    options.fileName=name;
    options.mimeType="image/jpeg";

    var params = new Object();
    params.fullpath = imageURI;
    params.name = name;
    params.formid = formid;

    options.params = params;
    options.chunkedMode = false;

    var ft = new FileTransfer();
    ft.upload( imageURI, "http://myserver/upload.php",
       function(result)
       {
            //upload successful   
            console.log('send result:');
            console.log(result);
            console.log('Hide #image'+imageNum+'_process');
            $('#image'+imageNum+'_process').hide(); 

            if ( $(".image_process:visible").length === 0)
            {
                console.log('Sending email');
                sendEmail(formid);

                // Delete localstorage if exists
                localStorage.removeItem(formid);

            }

       },
       function(error)
       {
          console.log('Error:');
          console.log(error);
            message('Upload unsuccessful, error occured while upload');
       },
       options
    );
}


function sendEmail(formid)
{
    console.log("sendEmail: "+formid);

    var postData = $( "#regform" ).serialize();

    $.ajax({
        type: 'POST',
        data: postData,
        url: 'http://myserver/email.php',
        success: function(data){
            console.log(data);
            console.log(data);
            console.log('Email sent');
        },
        error: function(){
            console.log(data);
            message('There was an error submitting the form');
        }
    });



}



// -----------------------------
// Network Functions
// -----------------------------


// IF ONLINE THEN SEND IMAGES



// Handle the online event
//
function onOnline()
{
    console.log("onOnline");
    networkState = 'online';
    sendLocalStorage();
}

function onOffline()
{
    console.log("onOffline");
    networkState = 'offline';
}

function checkConnection()
{
    var networkState = navigator.connection.type;

    console.log("Network State: "+networkState);

    if(networkState == 'none' || networkState == 'Connection.NONE')
    {
        return 'offline';   
    }
    else
    {
        return 'online';    
    }
}






// -----------------------------
// General Functions
// -----------------------------

function message(message)
{
    $('#messages').html(message);   
}

function convertToSlug(Text)
{
    return Text
       .toLowerCase()
       .replace(/ /g,'-')
       .replace(/[^\w-]+/g,'')
       ;
}

// Called if something bad happens.
function onFail(message)
{
    alert('onFail: ' + message);
}

我的HTML如下所示,我已将getPhoto()onClick事件放在包含<img>的div上,因此这将填充图像。

<div class="image-box" id="image1_div" onclick="getPhoto(pictureSource.PHOTOLIBRARY, 'image1'); return false;">
            <img style="display:none;width:50px;height:50px;" id="image1" src="" />
            <span class="image_process" id="image1_process" style="display: none">Uploading</span>
        </div>

        <div class="image-box" id="image2_div" onclick="getPhoto(pictureSource.PHOTOLIBRARY, 'image2'); return false;">
            <img style="display:none;width:50px;height:50px;" id="image2" src="" />
            <span class="image_process" id="image2_process" style="display: none">Uploading</span>
        </div>

        <div class="image-box" id="image3_div" onclick="getPhoto(pictureSource.PHOTOLIBRARY, 'image3'); return false;">
            <img style="display:none;width:50px;height:50px;" id="image3" src="" />
            <span class="image_process" id="image3_process" style="display: none">Uploading</span>
        </div>

        <div class="image-box" id="image4_div" onclick="getPhoto(pictureSource.PHOTOLIBRARY, 'image4'); return false;">
            <img style="display:none;width:50px;height:50px;" id="image4" src="" />
            <span class="image_process" id="image4_process" style="display: none">Uploading</span>
        </div>

1 个答案:

答案 0 :(得分:0)

我设法让它发挥作用。我必须为fileEntry.moveTo函数分配一个新的图像名称。我想知道在iOS模拟器(也许是其他人)中选择图像是否每次都为它指定相同的名称,因此需要设置一个新的唯一图像名称以允许存储多个图像。以下对我有用。

<style type="text/css">

.container div:nth-child(odd) {
    color:#F00;
}

.container div:nth-child(even) {
    color:#00F;
}

</style>
<div class="container">
   <div class="box-1">Lorem ipsum dolor sit amet.</div>
   <div class="box-2">Lorem ipsum dolor sit amet.</div>
   <div class="box-3">Lorem ipsum dolor sit amet.</div>
   <div class="box-4">Lorem ipsum dolor sit amet.</div>
</div>

注意:我将successCallback的movingImageSuccess作为函数传递,因此我可以在其中传递一个额外的变量“image”,用于稍后更新正确的图像。如果您没有传递额外的变量,则更有可能使用以下内容:

gotImageURI : function(fileEntry, image) {

        var d = new Date();
        var n = d.getTime();
        //new file name
        var newName = n + ".jpg";

        fileEntry.moveTo(gFileSystem.root, newName, function(fileEntry)
        {
            FileIO.movedImageSuccess(fileEntry, image); 
        }, FileIO.errorHandler);

    },