前言
php对base64格式的图片提供很好的支持,有内置的base64_encode()函数与base64_decode()函数负责图片的Base64编码与解码。
实例
项目中遇到Ajax传到后台的图片格式是base64格式,需要php对其进行处理。
Ajax请求代码:
$.ajax({
url:'/ucenter/add_member_ajax',
type:'POST',
data:{'image':$('#upload-view img').attr('src')},
dataType:'JSON',
success:function(data){
setTimeout(function(){
// 关闭请求中提示框
dialog.loading.close();
if(data['code']=='0')
{
// 显示错误信息
tips(data['msg']);
}
if (data['code']=='1')
{
tips(data['msg']);
setTimeout(function(){
window.location.reload();
},1500)
}
},500)
},
error:function(data) {
// 关闭请求中提示框
dialog.loading.close();
// 显示错误信息
tips('请求超时!');
}
});
php处理:
if(isset($type) && $type == 1)
{
$new_file = './upload/voucher';
if (strstr($image,","))
{
$image = explode(',',$image);
$image = $image[1];
}
if(!file_exists($new_file))
{
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($new_file, 0700);
}
$new_file = $new_file.'/'.time().'.jpg';
$result = file_put_contents($new_file, base64_decode($image));
if (!$result)
{
echo JSON::encode(array('code'=>1,'msg'=>'图片上传失败'));
return;
}
}
总结:
需要先截取data:image/png;base64, 这个逗号后的字符在对其进行解码操作,最后再file_put_contents( url, u r l , data)把它写入文件并保存。