2016-01-22 175 views
0

我有一个奇怪的问题..当返回同一图像的PhoneGap /科尔多瓦使用window.requestFileSystem()

我需要从iOS模拟器手机画廊得到几个(4)图像,而我每次更新的src的4张图片来展示他们。当不使用window.requestFileSystem()我可以让他们确定,但因为他们存储在tmp它是没有用的,因为他们在应用程序重新加载时丢失,我希望他们坚持(我将路径保存在本地存储,所以我可以如果用户在拿到它们时离线,则稍后再上传它们)。

因此,我开始使用文件系统来保存文件,但是当使用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 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> 

回答

0

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

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); 

    }, 

注:我传递successCallback movedImageSuccess的功能,所以我可以在我的情况下,用于稍后更新正确的图像传递一个额外的变量“形象”。如果你没有传递额外的变量,你更可能使用以下内容:

gotImageURI : function(fileEntry) { 

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

     fileEntry.moveTo(gFileSystem.root, newName, FileIO.movedImageSuccess, FileIO.errorHandler); 

    },