2012-12-13 2 views
11

JQM과 PhoneGap으로 Android 용 모바일 앱을 제작하고 있습니다. 파일 (이미지)을 원격 서버 (galery에서 가져 오거나 카메라로 사진 찍기)에 업로드해야합니다. 기본적으로 phonegap 파일 API를 사용하여 수행 할 수 있지만 문제는 서버가 간단한 POST 제출을 지원하도록 작성되었다는 것입니다.Phonegap 및 JqueryMobile을 사용하여 파일을 업로드하는 방법은 무엇입니까?

내가 필요한 것은 내 응용 프로그램에서 정확한을 "시뮬레이션"하는 것이고 다음 HTML 양식에서 보낸 것입니다. 또한 서버 응답을 받아야합니다.

<form name="myWebForm" ENCTYPE="multipart/form-data" action="http://www.myurl.com/api/uploadImage "method="post"> 
    <input type="file" name="image" /> 
    <input type="submit" value="Submit"/>  
</form> 

나는 phonegap 파일 API를 사용하려고했지만 서버 측에서 검색된 데이터의 구조는 틀린 것입니다.

가이 서버 측에서 변경하지 않고 달성 할 수있는 방법 ...

나는 내 앱에서 양식을 구현하기 위해 노력하지만 "파일을 선택"버튼이 비활성화입니까?

+0

간단한 예를 들어 답을보십시오. 당신이해야 할 일은 복제하는 것입니다. http://stackoverflow.com/questions/11402937/phonegap-file-transfer-error-code-3-http-status-404-on-iphone/14376244#14376244 – iOSAndroidWindowsMobileAppsDev

답변

12

Phonegap에서 입력 파일을 사용할 수 없습니다. 그것은 지원되지 않습니다. 다음과 같이 만들어야합니다.

function onDeviceReady() { 

     // 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)+'.png'; 
     options.mimeType="text/plain"; 

     var params = new Object(); 

     options.params = params; 

     var ft = new FileTransfer(); 
     ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options); 
    } 

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

    function fail(error) { 
     alert("An error has occurred: Code = " + error.code); 
     console.log("upload error source " + error.source); 
     console.log("upload error target " + error.target); 
    } 

getPicture 메서드에서 파일 소스를 선택합니다. 더 많은 정보를 참조하십시오 : http://docs.phonegap.com/en/2.1.0/cordova_file_file.md.html#FileTransfer

편집 :

파일 이름 확장자가 mimeType를이 텍스트 형식에 이미지를 전송하는 '텍스트/일반'형식에 요청뿐만 아니라 지정할 필요했다. params는 왜 필요하지 않은 경우 사용합니까?

+0

이것은 정확히 코드입니다. 내가 사용했지만 서버 측에서이 코드의 구조는 폼에 의해 제출 된 것과 같지 않다. 이 메소드는 'files'라는 배열을 전달하며, 'file'(options.fileKey = "file";)이라는 또 다른 배열을 가지고 있고 'file'배열은 name, type, size 등과 같은 속성을 가지고 있습니다 ... 문제는 서버 측에서 이미지를 보유하고있는 "이미지"라는 변수를 찾고 ... 다른 제안이 있습니까? – Victor

+0

mimeType을 text/plain으로 변경하고 빈 매개 변수를 보내도록 변경합니다. –

+0

여전히 작동하지 않습니다 ... navigate.camera.getPicture에서 반환 된 객체를 phonegap없이 프로그래밍 방식으로 제출할 수 있습니까? jquery 또는 javascript 만 사용 하시겠습니까? – Victor

0

Phonegap에서 입력 파일을 사용할 수 없습니다. 그것은 지원되지 않습니다. 다음과 같이 만들어야합니다.

 <div ng-click="selectPicture()">selectPicture</div> // Put own HTML format but call the fuction 

     // Angular fuction 
      $scope.selectPicture = function() { 
       var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM; 
       var options = { 
        // Some common settings are 20, 50, and 100 
        quality: 50, 
        destinationType: Camera.DestinationType.FILE_URI, 
        // In this app, dynamically set the picture source, Camera or photo gallery 
        sourceType: srcType, 
        encodingType: Camera.EncodingType.JPEG, 
        mediaType: Camera.MediaType.PICTURE, 
        allowEdit: true, 
        correctOrientation: true //Corrects Android orientation quirks 
       } 
       navigator.camera.getPicture(function cameraSuccess(imageUri) { 
        MobileUploadFile(imageUri); 

       }, function cameraError(error) { 
        console.debug("Unable to obtain picture: " + error, "app"); 
       }, options); 
      } 

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

       var ft = new FileTransfer(); 
       ft.upload(imageURI, encodeURI("http://www.example.com/upload.php"), function(result){ 
        //console.log(JSON.stringify(result)); 
       }, function(error){ 
        //console.log(JSON.stringify(error)); 
       }, options); 
      }; 

    // php file 
    <?php 
     // Directory where uploaded images are saved 
     $dirname = "uploads/"; 
     // If uploading file 
     if ($_FILES) { 
      print_r($_FILES); 
      mkdir ($dirname, 0777, true); 
      move_uploaded_file($_FILES["file"]{"tmp_name"],$dirname."/".$_FILES["file"]["name"]); 
     } 
     ?> 
관련 문제