图像数据未正确发送 - Ajax,Cordova

时间:2015-02-02 14:47:10

标签: javascript php jquery ajax cordova

以下代码是使用ajax拍照并发送到服务器,但图像数据未正确发送。

 <script>
      var pictureSource;   // picture source
      var destinationType; // sets the format of returned value 
      var image = "";


  document.addEventListener("deviceready", onDeviceReady, false);

        function onDeviceReady() {

        function alertDismissed() {
        };
            pictureSource = navigator.camera.PictureSourceType;
            destinationType = navigator.camera.DestinationType;
        }

 function capturePhoto() {
            navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
                quality: 50,
                destinationType: destinationType.DATA_URL
            });
        }

            function onPhotoDataSuccess(imageData) {

            var smallImage = document.getElementById('smallImage');

            smallImage.style.display = 'block';

            smallImage.src = "data:image/jpeg;base64," + imageData;

            image = "data:image/jpeg;base64," + imageData;

            alert("Image = "+image);
        }

     function onFail(message) {
            alert('Failed because: ' + message);
        }

    function submitFunction() {

        function alertDismissed() {
        };

        var dataString = 'image='+image;

        $.ajax({
        type: "POST",
        url: "url.php",
        data: dataString,
        cache: false,
        success: function(result){

        }
        });

        }
        </script>

        <input type="button" id="camera" class="btn btn-primary btn-large btn-block" value="Take Photo"  onclick="capturePhoto();"/>

        <input type="submit" class="btn btn-primary btn-large btn-block" value="Next"  onclick="submitFunction();" />

        <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />

图像显示正常,警报显示&#34;图像=数据:图像/ jpeg; base64,/ 9j / 4AAQSkZJRgABAQAAAQABAAD / 2wBDABALDA4M ...... o7cUAPFJR9KWmgP / 9k =&#34;。

但是,在下面的php中,$ _POST [&#39;图像&#39;]没有收到正确的数据,它缺少像&#39; +&#39;并用空格或换行替换它。因此,当我从其他页面的db返回时,图像无法正常显示。

url.php

$con=mysql_connect('server','user','password') or die("Failed to connect to MySQL: " . mysql_error());

$db=mysql_select_db('db',$con) or die("Failed to connect to MySQL: " . mysql_error()); 

$retval = mysql_query( "UPDATE tablename SET photo='".$_POST['image']."' WHERE ID='".$_POST['id']."'", $con );

echo $_POST['image'];

2 个答案:

答案 0 :(得分:1)

我给你的代码对我来说很有用。

在应用程序中使用它之前,以下工作非常重要: 你使用cordova / phonegap相机插件:cordova-plugin-camera

所以你必须通过捕获get base64编码图像后面的图像来设置选项

  navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
    destinationType: destinationType.DATA_URL });

onPhotoDataSuccess函数

function onPhotoDataSuccess(imageData) {
    upladImage(imageData);
}

函数uploadImage

function upladImage(imageData){
    $.ajax({

        type: "POST",
        url: "http://localhost/upload/up.php",
        data: {img_data:imageData},
        cache: false,
        contentType: "application/x-www-form-urlencoded",
        success: function (result) {
        alert("upload OK: "+ result);
        }

    });
}

img_data是服务器端的$ _​​POST [img_data]变量

PHP代码在服务器端(简单代码)

#from ajax post request save the post variable to $img
$img = $_POST["img_data"];

#folder to upload chmod 777 !!!
define('UPLOAD_DIR', 'images/');

#filename will be generated by timestamp 
$file = UPLOAD_DIR . time() . '.jpg'; 

#replace data header
$img = str_replace('data:image/png;base64,', '', $img);

#replace empty space
$img = str_replace(' ', '+', $img); 

#base64 decode
$data = base64_decode($img);

#save the file
$success = file_put_contents($file,$data);

#give feedback to your APP
if($success)
    echo "upload successfully";
else
    echo "an error occours while saving file";

ajax post request方法是文件传输插件上传功能的一个很好的替代方法,因为某些android版本的文件传输上传功能有问题。 (所以这是我的经历)

也很重要:你必须在你的html文件中包含cordova和jquery库。

答案 1 :(得分:0)

你的base64图像字符串将包含url编码中具有特殊含义的字符,你需要对它们进行编码

var dataString = 'image='+encodeURIComponent(image);

或更容易

data: {"image":image},