1.注册input file标签的onchange事件;
2.检查图片格式;
3.检查图片大小;
4.压缩图片
5.上传图片至服务器;
前端代码:
document.getElementById('img-file').addEventListener('change', function (event){
var that=this;
var file = that.files[0];
if (file) {
var rFilter = /^(image\/jpeg|image\/png|image\/jpg)$/i; // 检查图片格式
if (!rFilter.test(file.type)) {
alert("请选择jpeg、png、jpg格式的图片");
return;
}
}
var fileSize = Math.round(that.files[0].size/1024/1024) ; //以M为单位
if(fileSize>3){
alert("请上传小于3M的图片");
return;
} //压缩后上传
compress(event.target.files[0],fileSize,function(base64_data){
$.ajax({
type:'post',
url:ApiUrl+'/index.php?act=sns_album&op=base64_upload',
data:{key:key,imgBase64:base64_data},
dataType:'json',
success: function(result){
callBack(result);
}
});
}); },true); function compress(res,fileSize,callBack) {
//res代表上传的图片base64位,fileSize大小图片的大小
var img = new Image();
var maxW = 800; //设置最大宽度
img.onload = function () {
var cvs = document.createElement('canvas'),
ctx = cvs.getContext( '2d');
if(img.width > maxW) {
img.height *= maxW / img.width;
img.width = maxW;
}
cvs.width = img.width;
cvs.height = img.height;
ctx.clearRect(0, 0, cvs.width, cvs.height);
ctx.drawImage(img, 0, 0, img.width, img.height);
var compressRate = getCompressRate(1,fileSize);
//*将image对象转成base64*
var dataUrl = cvs.toDataURL('image/jpeg', compressRate);
if(typeof callBack=='function') callBack(dataUrl);
}
img.src = res;
}
服务器:
public function base64_uploadOp(){
header('Content-type:text/html;charset=utf-8');
$base64_image_content = $_POST['imgBase64'];
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
$type = $result[2];
$member_id = $this->member_info['member_id']; $date = date("Ym");
$new_file =BASE_UPLOAD_PATH.DS."chat/".$date.DS;
if (!file_exists($new_file)) {
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($new_file, 0700);
}
$file_name=time();
$new_file = $new_file . $file_name . ".{$type}";
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
$data = array();
$data['file_id'] = $file_name;
$data['file_name'] = $new_file;
$data['file_url'] =UPLOAD_SITE_URL.DS."chat/".$date.DS.$file_name . ".{$type}";
return json_encode($data);
} else {
exit("文件保存失败");
}
}else{
exit("文件转换失败");
}
}