2012-12-17 4 views
6

Phonegap으로 내 서버에 파일을 업로드하려고합니다. 오류가 말한다 때 현재 붙어 :Phonegap : InvalidCastException을 사용하여 이미지 업로드

InvalidCastException 
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"] 

HTML + 자바 스크립트

<!DOCTYPE html> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    <meta name="format-detection" content="telephone=no" /> 
    <title>File Transfer Example</title> 

</head> 
<body> 
    <button id="uploadPhotoButton">Upload a Photo</button> 

    <script type="text/javascript" src="cordova-2.2.0.js"></script> 
    <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script> 
    <script type="text/javascript" src="js/jquery.mobile-1.2.0.min.js"></script> 
    <script type="text/javascript" src="js/camera.js"></script> 
    <script type="text/javascript"> 

    $(document).one("pause", function() { 
     console.log('Paused.'); 
    }); 

    $(document).one("resume", function() { 
     console.log('Resumed.'); 
    }); 

    $(document).one("deviceready", function() { 
     console.log('Device is ready.'); 
    }); 

    $(document).one("backbutton", function() { 
     console.log('Back button pressed.'); 
    }); 

    $(document).ready(function() { 
     console.log('DOM is ready.'); 

     $(document).on("click", "#uploadPhotoButton", function (e) { 
      console.log('clicked button'); 
      getImage(); 
     }); 


     function getImage() { 
      // Retrieve image file location from specified source 
       navigator.camera.getPicture(uploadPhoto, function (message) { 
        alert('get picture failed'); 
       }, { 
        quality: 50, 
        destinationType: navigator.camera.DestinationType.FILE_URI, 
        sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY 
       } 
      ); 

     } 

     function uploadPhoto(imageURI) { 
      var options = new FileUploadOptions(); 
      options.fileKey = "file"; 
      options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1); 
      options.mimeType = "image/jpeg"; 

      var params = new Object(); 
      params.value1 = "test"; 
      params.value2 = "param"; 

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

      var ft = new FileTransfer(); 
      ft.upload(imageURI, "http://my.server.co.nz/pages/fileupload", win, fail, options); 
     } 

     function win(r) { 
      console.log("Code = " + r.responseCode); 
      console.log("Response = " + r.response); 
      console.log("Sent = " + r.bytesSent); 
      alert(r.response); 
     } 

     function fail(error) { 
      alert("An error has occurred: Code = " = error.code); 
     } 
    }); 

    </script> 
    </body> 
</html> 

전체 오류 로그.

GapBrowser_Navigated :: /app/www/index.html#/app/www/uploadtest.html 
Log:"clicked button" 
The thread '<No Name>' (0xf55026a) has exited with code 0 (0x0). 
The thread '<No Name>' (0xe3f0326) has exited with code 0 (0x0). 
INFO: AppDeactivated 
INFO: AppActivated 
Log:"Paused." 
The thread '<No Name>' (0xf1a02e6) has exited with code 0 (0x0). 
Log:"Resumed." 
The thread '<No Name>' (0xf2a01d2) has exited with code 0 (0x0). 
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"] 
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll 
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll 
InvalidCastException 
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"] 
A first chance exception of type 'System.NullReferenceException' occurred in Lion.MyApp.dll 
The thread '<No Name>' (0xfdc025e) has exited with code 0 (0x0). 
Log:"Error in error callback: FileTransfer1325332352 = ReferenceError: Invalid left-hand side in assignment" 
The thread '<No Name>' (0xfa60286) has exited with code 0 (0x0). 

누구나이 작업을 수행하는 방법에 대한 아이디어가 있습니까?

감사합니다.

w

+0

이 업데이트에서 Windows Phone Emulator에서이 문제를 해결할 수 없습니다. 나는 이것을 iPhone에서 테스트 해 보았습니다. – wenbert

답변

1

나는 당신이 옵션 값을 잘못 만들고 있다고 생각합니다. JSON 또는 실제 객체를 전달해야합니까?

지금은 텍스트가 포함 된 배열을 전달하고 있습니다.

options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"] 

오류에는 직렬화 문제가있는 것으로 보입니다.

0

당신과 비슷한 문제가 있습니다. mimeType 매개 변수를 'text/plain'으로 변경하면서이 문제를 해결했습니다.

params를 사용 하시겠습니까? 거짓이라면 빈 매개 변수를 보내야한다고 생각합니다.

+0

mimeType에'text/plain'을 사용해 보았는데 작동하지 않았습니다. – wenbert

0

나는이 문제 이전에, 그것을 현금으로 촬영 한 사진을 저장하지 않을 수 있습니다 먼저 HTML에 이미지를 준비하려고하고, 탐색기에서 직접을 해달라고했다, 나는 가정 내 솔루션에서)

그럼 내가 그 안에 이미지의 모든 변수를 설정 ... ID = 'camera_image'

IMG 아이디 = 'camera_image'와 이미지 다케을하고 난 당신 같은 (업로드하기 다음 코드에서 볼 수 있습니다).

여기에이 개 기능을 내가 사용되는 :

function takephoto(){  

     navigator.camera.getPicture(  
     function(uri){ 
      $('#camera_image').show(); 
      var img = document.getElementById('camera_image'); 
      img.style.visibility = "visible"; 
      img.style.display = "block"; 
      img.src = uri; 
      uploadPhoto(img);      
      alert("Success"); 
     }, 
     function(e) { 
      console.log("Error getting picture: " + e); 
     }, 
     { 
      quality: 50, 
      destinationType: navigator.camera.DestinationType.FILE_URI 
     }); 

     // Get URI of picture to upload 
     var img = document.getElementById('camera_image'); 
     var imageURI = img.src; 
     if (!imageURI || (img.style.display == "none")) { 
       alert("Take picture or select picture from library first."); 
       return; 
     } 
} 

기존 사진을 선택해 : 업로드 기능에

function choosephoto(){ 
    navigator.camera.getPicture(
     function(uri) { 
      $('#camera_image').show(); 
      var img = document.getElementById('camera_image'); 
      img.style.visibility = "visible"; 
      img.style.display = "block"; 
      img.src = uri; 
      uploadPhoto(img); 
     }, 
     function(e) { 
      console.log("Error getting picture: " + e); 
     }, 
     { 
      quality: 50, 
      destinationType: navigator.camera.DestinationType.FILE_URI, 
      sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM 
     });    

     // Get URI of picture to upload 
     var img = document.getElementById('camera_image'); 
     var imageURI = img.src; 
     if (!imageURI || (img.style.display == "none")) { 
      alert("please select a pic first"); 
      return; 
     } 

    } 

: 기능 uploadPhoto (IMG) { imageURI = img.src. ..

ps : 내 코드를 포맷하는 데 유감스럽게도 잘 해결되지 않습니다.

+0

@wenbert 형식을 수정 해 주셔서 감사합니다. –

1

$ (document) .ready의 인라인 함수 호출을 벗어난 getImage, uploadImage, win을 넣습니다.

실제로 win과 fail에 대한 참조가 닫히고 전화 갭은 해당 메소드에 직접 액세스하려고 시도 할 때 null로 표시됩니다. Phonegap은 아마도 숨겨진 함수 대신에 전역 함수를 기대합니다.

PhoneGap의 코드가 사이드 자바 스크립트 컨텍스트를 실행하기 때문에 실제 자바 스크립트에서 작동하는 것이 phonegap에서 올바르게 작동하지 않을 수 있습니다.

+0

Nope. getImage와 다른 메소드들을 jQuery의'$ (document) .ready' 함수의 외부에 두는 것은 작동하지 않았습니다. 나는 똑같은 오류가있다. – wenbert

관련 문제