以下代码是使用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="" />
图像正确显示,并且警报显示“图像= data:image / jpeg; base64,/ 9j / 4AAQSkZJRgABAQAAAQABAAD / 2wBDABALDA4M ... o7cUAPFJR9KWmgP / 9k =“。
但是,在下面的php中,$ _POST ['image']没有接收到正确的数据,它丢失了一些字符,例如'+',并且还用空格或换行代替了它。因此,当我从其他页面的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'];
您的base64图片字符串将包含url编码中具有特殊含义的字符,您需要对其进行编码
var dataString = 'image='+encodeURIComponent(image);
或更容易
data: {"image":image},
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句