将图像从Ionic App发布到PHP Server

时间:2015-10-28 07:05:53

标签: image cordova ionic phpmailer

我正在使用Ionic Framework构建移动应用程序。我需要让用户从他们的手机图库中选择一张图片(使用Cordova ImagePicker),然后点击上传按钮。用户单击“上载”按钮后,必须将图像和用户名传递给服务器,然后服务器处理图像和用户名,并使用PHPMailer类将其邮寄到指定的电子邮件ID。截至目前,我已成功将用户名发送到服务器并成功将其转发为电子邮件,但我不知道如何将图像与其一起发送。

请帮忙!

注意:我根本不想将图像上传到服务器,或者我可以使用Cordova文件传输插件。我只想将图像传递给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 = "support@example.com";  // SMTP username
            $mail->Password = "password"; // SMTP password
            $mail->From = "support@example.com";
            $mail->FromName = "Example";
            $mail->AddAddress("abc@example.com", "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!";
    }
?>

2 个答案:

答案 0 :(得分:0)

您已将代码基于一个过时的示例,并且您正在运行旧版本的PHPMailer,因此我建议您update it。我还建议使用composer加载PHP库。

PHPMailer包括an example script,其中显示了如何使用文件元素处理表单并通过电子邮件发送它。

这是重要的部分:

objectPump

我能看到的唯一复杂因素是你的文件数据不会在$ _FILES中 - 你需要确保你的解码JSON提交实际上包含了你的想法,所以在你使用之前验证所有内容。

答案 1 :(得分:-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);
              }