2015-10-28 106 views
-2

我正在使用離子框架構建移動應用程序。我需要讓用戶從他們的手機庫中選擇一個圖像(使用Cordova ImagePicker)並點擊上傳按鈕。一旦用戶點擊上傳按鈕,圖像和用戶名必須傳遞到服務器,然後服務器處理圖像和用戶名,並使用PHPMailer類將其郵寄到指定的電子郵件ID。到目前爲止,我成功地將用戶名發送到服務器,併成功將其轉發爲電子郵件,但我不知道如何隨圖像一起發送圖像。從離子應用程序發佈圖像到PHP服務器

請幫忙!

注意:我不想將圖像上傳到服務器,或者我可以使用Cordova File Transfer插件。我只是想將圖像傳遞給PHPMailer類併發送郵件。

客戶端

.controller('UploadCtrl', function($scope,$cordovaImagePicker,$http) { 

    $scope.collection = { 
     selectedImage : '' 
    }; 

    $scope.takePicture = function() { 
     var options = { 
       maximumImagesCount:1, 
       width: 800, 
       height: 800, 
       quality: 80   
      }; 

      $cordovaImagePicker.getPictures(options).then(function (results) { 
       for (var i = 0; i < results.length; i++) { 
        $scope.collection.selectedImage = results[i]; 
        window.plugins.Base64.encodeFile($scope.collection.selectedImage, function(base64){ 
         $scope.collection.selectedImage = base64; 
        }); 
       } 
      }, function(error) { 
       console.log('Error: ' + JSON.stringify(error)); 
      }); 
     }; 

     $scope.data = {}; 
     $scope.upload = function() { 
       var link = 'http://example.com/upload.php'; 
       $http.post(link, {username : "xyz"}).then(function (res){ 
       $scope.response = res.data; 
       console.log($scope.response); 
     }); 
    }; 
}) 

服務器端

<?php 

    if (isset($_SERVER['HTTP_ORIGIN'])) { 
     header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); 
     header('Access-Control-Allow-Credentials: true'); 
     header('Access-Control-Max-Age: 86400');  
    } 


    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { 

     if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) 
      header("Access-Control-Allow-Methods: GET, POST, OPTIONS");   

     if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) 
      header("Access-Control-Allow-Headers:   
      {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); 

     exit(0); 
    } 


    $postdata = file_get_contents("php://input"); 
    if (isset($postdata)) { 
     $request = json_decode($postdata); 
     $username = $request->username; 

     if ($username != "") { 
      echo "Server returns: " . $username; 
      require("PHPMailer/class.phpmailer.php"); 
      $mail = new PHPMailer(); 
      $mail->IsSMTP(); 
      $mail->Host = "localhost"; // specify main and backup server 
      $mail->SMTPAuth = true;  // turn on SMTP authentication 
      $mail->Username = "[email protected]"; // SMTP username 
      $mail->Password = "password"; // SMTP password 
      $mail->From = "[email protected]"; 
      $mail->FromName = "Example"; 
      $mail->AddAddress("[email protected]", "ABC"); 
      $mail->WordWrap = 50; 
      //$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); 
      $mail->IsHTML(true); 
      $mail->Subject = "New List Uploaded"; 
      $mail->Body = $username; 
      $mail->AltBody = "Alternate Body"; 

      if(!$mail->Send()) 
      { 
       echo "Message could not be sent. <p>"; 
       echo "Mailer Error: " . $mail->ErrorInfo; 
       exit; 
      } 
      echo "Message has been sent"; 
     } 
     else { 
      echo "Empty username parameter!"; 
     } 
    } 
    else { 
     echo "Not called properly with username parameter!"; 
    } 
?> 
+0

你好,所以你正面臨問題上傳圖像在服務器上? –

+0

嘿!那種。我如何將$ scope.collection.selectedImage傳遞給服務器?我不想將圖像上傳到服務器。我只是想將圖像傳遞給PHPMailer類併發送郵件。 – vkm

+0

我完全不知道如何做到這一點。一個描述性的說明會有所幫助。 – vkm

回答

-2
function getPhotoFromGallary(source) { 
       navigator.camera.getPicture(uploadProfileImage, onFailGallary, { 
        quality: 50, 
        destinationType: destinationType.FILE_URI, 
        correctOrientation: true, 
        sourceType: source } 
              ); 
       } 

       function onFailGallary(message) { 
       // alert('Failed because: ' + message); 

       } 

     function uploadProfileImage(imageURI) { 
       console.log(imageURI); 
       var UserId = localStorage.getItem('UserId'); 
       var img = document.getElementById('profileImageId'); 
       img.src = imageURI; 
       var options = new FileUploadOptions(); 
       options.fileKey="file"; 
       options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1); 
       options.mimeType="image/jpeg"; 
       var ft = new FileTransfer(); 
       ft.upload(imageURI, encodeURI("http://androidmobiapps.com/longspan/webservices/uploaduserimg?user_id="+UserId+""), winProfile, failProfile, options); 
       } 
       function winProfile(r) { 
       console.log("Code = " + r.responseCode); 
       console.log("Response = " + r.response); 
       console.log("Sent = " + r.bytesSent); 

       } 
       function failProfile(error) { 
       console.log("upload error source " + error.source); 
       console.log("upload error target " + error.target); 
       } 
+0

請爲您的答案添加一些解釋以幫助用戶在將來。 – Brody

0

你根據你的代碼在一個過時的例子,你正在運行的是舊版本的PHPMailer的,所以我建議你update it。我也推薦使用composer來加載你的PHP庫。

PHPMailer包含an example script,它顯示瞭如何處理帶有文件元素的表單並通過電子郵件發送。

這是重要的部分:

<?php 
/** 
* PHPMailer simple file upload and send example 
*/ 
$msg = ''; 
if (array_key_exists('userfile', $_FILES)) { 
    // First handle the upload 
    // Don't trust provided filename - same goes for MIME types 
    // See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation 
    $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name'])); 
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { 
     // Upload handled successfully 
     // Now create a message 
     // This should be somewhere in your include_path 
     require 'PHPMailerAutoload.php'; 
     $mail = new PHPMailer; 
     $mail->setFrom('[email protected]', 'First Last'); 
     $mail->addAddress('[email protected]', 'John Doe'); 
     $mail->Subject = 'PHPMailer file sender'; 
     $mail->msgHTML("My message body"); 
     // Attach the uploaded file 
     $mail->addAttachment($uploadfile, 'My uploaded file'); 
     if (!$mail->send()) { 
      $msg = "Mailer Error: " . $mail->ErrorInfo; 
     } else { 
      $msg = "Message sent!"; 
     } 
    } else { 
     $msg = 'Failed to move file to ' . $uploadfile; 
    } 
} 
?> 

我能看到的唯一複雜的是,你的文件數據將不會在$ _FILES - 你需要確保你的解碼JSON提交實際上包含了你在想什麼它確實如此,所以在使用它之前驗證一切。

+0

嘿謝謝你的回覆!我如何發送$ scope.collection.selectedImage作爲json數據? – vkm

+0

你需要檢查科爾多瓦文檔 – Synchro

相關問題