2015-05-29 69 views
17

我正在研究離子聊天應用程序,用戶可以將照片作爲其消息的一部分上載。我正在尋找一種方法將圖像上傳到我的虛擬主機服務器,以便以後通過URL檢索。從相機/照片庫上載離子應用程序圖像

問題是我無法將它上傳到我的網絡服務器。

我使用這兩個插件:

  • org.apache.cordova.file轉移
  • 科爾多瓦 - 插件相機

當我運行在Xcode模擬器應用程序和從設備光盤庫中選擇一張照片,控制檯給我以下信息:

  • File Transfer Finished with response code 200
  • void SendDelegateMessage(NSInvocation *): delegate (webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode>
  • SUCCESS: ""

這是我目前使用的代碼:

app.controller('HomeController', function($rootScope, $scope, $cordovaCamera, $ionicActionSheet, $cordovaFileTransfer){ ... 

// open PhotoLibrary 
    $scope.openPhotoLibrary = function() { 
     var options = { 
      quality: 100, 
      destinationType: Camera.DestinationType.FILE_URI, 
      sourceType: Camera.PictureSourceType.PHOTOLIBRARY, 
      allowEdit: true, 
      encodingType: Camera.EncodingType.JPEG, 
      popoverOptions: CameraPopoverOptions, 
      saveToPhotoAlbum: false 
     }; 

     $cordovaCamera.getPicture(options).then(function(imageData) { 

      //console.log(imageData); 
      //console.log(options); 

      var url = "http://mydomein.com/upload.php"; 
      //target path may be local or url 
      var targetPath = imageData; 
      var filename = targetPath.split("/").pop(); 
      var options = { 
       fileKey: "file", 
       fileName: filename, 
       chunkedMode: false, 
       mimeType: "image/jpg" 
      }; 
      $cordovaFileTransfer.upload(url, targetPath, options).then(function(result) { 
       console.log("SUCCESS: " + JSON.stringify(result.response)); 
       alert("success"); 
       alert(JSON.stringify(result.response)); 
      }, function(err) { 
       console.log("ERROR: " + JSON.stringify(err)); 
       alert(JSON.stringify(err)); 
      }, function (progress) { 
       // constant progress updates 
       $timeout(function() { 
        $scope.downloadProgress = (progress.loaded/progress.total) * 100; 
       }) 
      }); 

     }, function(err) { 
      // error 
      console.log(err); 
     }); 
    } 


這是我的upload.php的文件:

<?php 
// move_uploaded_file($_FILES["file"]["tmp_name"], $cwd . '/files/images/'); 
move_uploaded_file($_FILES["file"]["tmp_name"], "/files/images"); 
?> 

回答

19

經過一番挖掘和嘗試,我終於得到它的工作。

這是我想出了代碼:

// open PhotoLibrary 
    $scope.openPhotoLibrary = function() { 
     var options = { 
      quality: 50, 
      destinationType: Camera.DestinationType.FILE_URI, 
      sourceType: Camera.PictureSourceType.PHOTOLIBRARY, 
      allowEdit: true, 
      encodingType: Camera.EncodingType.JPEG, 
      popoverOptions: CameraPopoverOptions, 
      saveToPhotoAlbum: false 
     }; 

     $cordovaCamera.getPicture(options).then(function(imageData) { 

      //console.log(imageData); 
      //console.log(options); 
      var image = document.getElementById('tempImage'); 
      image.src = imageData; 

      var server = "http://yourdomain.com/upload.php", 
       filePath = imageData; 

      var date = new Date(); 

      var options = { 
       fileKey: "file", 
       fileName: imageData.substr(imageData.lastIndexOf('/') + 1), 
       chunkedMode: false, 
       mimeType: "image/jpg" 
      }; 

      $cordovaFileTransfer.upload(server, filePath, options).then(function(result) { 
       console.log("SUCCESS: " + JSON.stringify(result.response)); 
       console.log('Result_' + result.response[0] + '_ending'); 
       alert("success"); 
       alert(JSON.stringify(result.response)); 

      }, function(err) { 
       console.log("ERROR: " + JSON.stringify(err)); 
       //alert(JSON.stringify(err)); 
      }, function (progress) { 
       // constant progress updates 
      }); 


     }, function(err) { 
      // error 
      console.log(err); 
     }); 
    } 

和域服務器上upload.php的代碼:

<?php 

// if you want to find the root path of a folder use the line of code below: 
//echo $_SERVER['DOCUMENT_ROOT'] 


if ($_FILES["file"]["error"] > 0){ 
echo "Error Code: " . $_FILES["file"]["error"] . "<br />"; 
} 
else 
{ 
echo "Uploaded file: " . $_FILES["file"]["name"] . "<br />"; 
echo "Type: " . $_FILES["file"]["type"] . "<br />"; 
echo "Size: " . ($_FILES["file"]["size"]/1024) . " kilobytes<br />"; 

if (file_exists("/files/".$_FILES["file"]["name"])) 
    { 
    echo $_FILES["file"]["name"] . " already exists. No joke-- this error is almost <i><b>impossible</b></i> to get. Try again, I bet 1 million dollars it won't ever happen again."; 
    } 
else 
    { 
    move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/vhosts/yourdomain.com/subdomains/domainname/httpdocs/foldername/images/".$_FILES["file"]["name"]); 
    echo "Done"; 
    } 
} 
?> 
+0

如果您使用其他服務器,如Node.js和Express.js,那麼該怎麼辦? –

3

應用我是buildi對於一家公司而言,ng具有相同的問題,我們所做的只是將該映像作爲base64字符串發佈到我們的服務器。然後,您可以簡單地從數據庫中拉出字符串並將其顯示在div中。我們使用NgCordova相機,然後只傳入takePhoto函數中的數據。

$scope.takePhoto = function() { 
      $ionicScrollDelegate.scrollTop(); 
      console.log('fired camera'); 
      $scope.uploadList = false; 
      $ionicPlatform.ready(function() { 
       var options = { 
        quality: 100, 
        destinationType: Camera.DestinationType.DATA_URL, 
        sourceType: Camera.PictureSourceType.CAMERA, 
        allowEdit: false, 
        encodingType: Camera.EncodingType.PNG, 
        targetWidth: 800, 
        targetHeight: 1100, 
        popoverOptions: CameraPopoverOptions, 
        saveToPhotoAlbum: false 
       }; 
       $cordovaCamera.getPicture(options).then(function (imageData) { 
        $ionicLoading.show({ 
         template: 'Processing Image', 
         duration: 2000 
        }); 
        $scope.image = "data:image/png;base64," + imageData; 
        if (ionic.Platform.isAndroid() === true) { 
         $scope.Data.Image = LZString.compressToUTF16($scope.image); 
         $scope.Data.isCompressed = 1; 
        } else { 
         $scope.Data.Image = $scope.image; 
         $scope.Data.isCompressed = 0; 
        } 
        if ($scope.tutorial) { 
         $scope.showAlert("Instructions: Step 3", '<div class="center">Now that you have taken a photo of the POD form, you must upload it to the server. Press the upload doc button in the bottom right of the screen.</div>'); 
        } 
        $scope.on('') 
       }, function (err) { 
        console.log(err); 
       }); 
      }, false); 
     }; 

$scope.UploadDoc = function() { 
      var req = { 
       method: 'POST', 
       url: ffService.baseUrlAuth + 'cc/upload', 
       headers: { 
        'x-access-token': ffService.token 
       }, 
       data: $scope.Data 
      }; 
      if ($scope.Data.Image === null || $scope.Data.Value === '') { 
       $scope.showAlert("Uh Oh!", '<div class="center">Please take a photo of your document before attempting an upload.</div>'); 
      } else { 
       $http(req).success(function (data, status, headers, config) { 
        localStorage.setItem('tutorial', false); 
        $scope.tutorial = false; 
        $scope.getUploads($scope.PODOrder.OrderNo); 
        $scope.showAlert("Success!", '<div class="center">Your Document has been successfully uploaded!</div>'); 
        $scope.uploadList = true; 
       }).error(function (data, status, headers, config) { 
        $rootScope.$broadcast('loading:hide'); 
        $scope.showAlert("Something went wrong!", '<div class="center">Please make sure you have an internet connection and try again.</div>'); 
       }).then(function(data, status, headers, config){ 
        $scope.Data.Image = null; 
       }); 
      } 
     }; 
+0

嗨,你可以分享的HTML請,還怎麼能我傳遞了授權或令牌。 –

+0

也如何添加我的服務器URL,在哪個部分。 和我需要一個使用PHP或不。 –

相關問題