我正在设计phonegap中的应用。我发送多个base64图像到php webservice。现在我需要解码所有这些base64图像并将它们保存到数据库中。
我希望有最好的解决方案。谢谢。
这是我将base64值分配给隐藏输入类型的代码。
for(i = 0; i< image.length;i++){
$('#table_postad').append('<input type="hidden" value="'+image[i]+'" name="ad_image'+i+'" class="ad_image"/>');
imageArray.push(document.getElementsByClassName("ad_image")[i].value);
}
以下是连接服务器的代码:
var server = 'http://example.com/webServiceForProject/';
function sendDataToServer(){
alert("access");
var datas = $("#form_description").serialize();//form_description is id for form
console.log(datas);
$.ajax({
type: 'POST',
data: datas,
url: server+'insert.php',
success: function(data){
alert(data);
},
error: function(){
alert('There was an error adding your comment');
}
});
}
这是php代码:
<?php
define('UPLOAD_DIR', 'images/');
$adPhotos = array();
$i=0;
while(isset($_POST["ad_image".$i])){
array_push($adPhotos,($_POST["ad_image".$i]));
$i++;
echo($adPhotos[i]);
}
$j = 0;
while(sizeof($adPhotos)){
$adPhotos[$j]= str_replace('data:image/png;base64,', '', $adPhotos[$j]);
$adPhotos[$j]= str_replace(' ', '+', $adPhotos[$j]);
$file[$j] = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file[$j], $data[$j]);
j++;
}
//insert code here.....
?>
答案 0 :(得分:2)
使用php的base64_decode对图片进行解码并将其保存到您的数据库中(例如使用mysql_query
和INSERT INTO...
语句。
答案 1 :(得分:0)
Ram,你不必将图像转换为base64。请使用此代码。
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {}
function browseImage() {
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},{
quality: 80,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://example.com/api/upload.php", win, fail, options);
}
function win(r) {
console.log("Response Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
console.log("Error: Code = " = error.code);
}
</script>
<input type="button" onclick= "browseImage()" value="Browse Image" />
//Server: PHP code to upload file
$img_name = $time."jpg";
if(move_uploaded_file($_FILES["file"]["tmp_name"], "folder/".$img_name)){ //upload files in location folder/
//use mysql query to save the filename. (mysql_query("insert into tbl_name(image) values('$img_name')"))
}