PHP常用函数之base64图片上传功能详解

yipeiwu_com6年前PHP代码库

本文实例讲述了PHP常用函数之base64图片上传功能。分享给大家供大家参考,具体如下:

HTML页面代码:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<img id="articleImg" width="180" height="100">
<input type="file" value="上传" id="articleImgBtn" />
<script type="text/javascript" src = 'jquery-2.1.4.min.js'></script>
<script type="text/javascript">
$('#articleImgBtn').change(function(){
run(this, function (data) {
uploadImage(data);
});
});
function run(input_file, get_data) {
/*input_file:文件按钮对象*/
/*get_data: 转换成功后执行的方法*/
if (typeof (FileReader) === 'undefined') {
alert("抱歉,你的浏览器不支持 FileReader,不能将图片转换为Base64,请使用现代浏览器操作!");
} else {
try {
/*图片转Base64 核心代码*/
var file = input_file.files[0];
//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
if (!/image\/\w+/.test(file.type)) {
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.onload = function () {
get_data(this.result);
}
reader.readAsDataURL(file);
} catch (e) {
alert('图片转Base64出错啦!' + e.toString())
}
}
}
function uploadImage(img) {
//判断是否有选择上传文件
var imgPath = $("#articleImgBtn").val();
if (imgPath == "") {
alert("请选择上传图片!");
return;
}
//判断上传文件的后缀名
var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp') {
alert("请选择图片文件");
return;
}
$.ajax({
type: "POST",
url: 'http://localhost/123.php',
// data: {file: img.substr(img.indexOf(',') + 1)}, //视情况将base64的前面字符串data:image/png;base64,删除
data: {file: img}, //视情况将base64的前面字符串data:image/png;base64,删除
cache: false,
success: function(data) {
var return_info = JSON.parse(data);
if(return_info.status){
$("#articleImg").attr('src', return_info.path);
alert("上传成功");
}else{
alert(return_infoerr_info);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("上传失败,请检查网络后重试");
}
});
}
</script>
</body>
</html>

PHP 处理代码:

function upload_image($file_data){
$upload_result = array('status' => true, 'msg'=>'','err_info'=>'');
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file_data, $result)) {
//处理base64字符串
$img_base64 = str_replace($result[1], '', $file_data);
$img_base64 = str_replace('=', '', $img_base64);
$source_img = base64_decode($img_base64);
//判断文件大小
$file_size =
//上传目录
$basedir = './img_test';
//后缀
$img_suffix = $result[2];//文件后缀
//文件名
// $filename = uniqid();//文件名
$filename = date('YmdHis',time());//文件名
//文件完整路径
$filepath = $basedir . "/" . $filename . "." . $img_suffix;
//目录若果不存在,则创建目录
if(!is_dir($basedir)){
mkdir($basedir);
chmod($basedir,0777);
}
//上传文件
try {
file_put_contents($filepath, $img_base64);
$filepath = substr($filepath, 1);
$upload_result = array('status' => true, 'msg'=>'上传成功','err_info'=>'','path'=>$filepath);
return $upload_result;
} catch (Exception $e) {
$upload_result = array('status' => false, 'msg'=>'上传失败','err_info'=>$e->getMessage());
return $upload_result;
}
// if (file_put_contents($filepath, base64_decode(str_replace($result[1], '', $file_data)))) {
// //$size = getimagesize($filepath);
// $filepath = substr($filepath, 1);
// //$arr['filepath'] = $filepath;
// //$arr['size'] = $size[3];
// return $filepath;
// }else{
// return false;
// }
}else{
$upload_result = array('status' => false, 'msg'=>'上传失败','err_info'=>'请携带base64字符串的前缀');
return $upload_result;
}
}
$res = upload_image($file_data);
echo json_encode($res);


相关文章

PHP排序算法系列之归并排序详解

归并排序 归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得...

phpMyAdmin通过密码漏洞留后门文件

phpMyAdmin通过密码漏洞留后门文件

默认 phpMyAdmin:用户名 root 密码 root 或空登陆。 版本 2.11.3~2.11.4:用户名 'localhost'@'@" 登陆,无需密码。 版本...

功能强大的php分页函数

分页是每一个程序需要去理解的东西,学习过的几门语言中我发现分页原理都是一样的,下面为php初学者分析一下php分页实现与最后面补充了一个超级强大的分页函数。 文章内容分页主要有两个办法:...

php实现微信公众平台账号自定义菜单类

微信公众平台服务号可申请自定义菜单了,其它的号暂时不支持自定义菜单了,这个不但可以使用api来操作,还可以直接在后台定义菜单与参数哦。 服务号可以申请自定义菜单;使用QQ登录的公众号,可...

PHP数据对象映射模式实例分析

本文实例讲述了PHP数据对象映射模式。分享给大家供大家参考,具体如下: 将对象和数据存储映射起来,对一个对象的操作映射为对数据存储的操作。 例如在代码中new 一个对象,使用数组对象映射...