2016-01-22 217 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); 

    },