首先介绍大家熟知的form表单提交(file)方式:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="uploadImage.php" method="post" enctype="multipart/form-data">
上传:<input type="file" name="img"/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
需要注意的是enctype属性:
enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。
默认地,表单数据会编码为 “application/x-www-form-urlencoded”。
就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 “+” 加号,
特殊符号转换为 ASCII HEX 值)。
图片上传时设置为:enctype=”multipart/form-data”
后台php代码
通过$_FILES变量获取相关值
Array (
[name] => 4550857839873941.jpg
[type] => image/jpeg
[tmp_name] => C:\Users\Administrator\AppData\Local\Temp\php2136.tmp
[error] => 0
[size] => 578824
)
下面是php代码,我用的是thinkphp框架
public function uploadImage(){
if($_FILES["error"] == 0){
$typeArr = explode("/", $_FILES["type"]);
$imgType = array("png","jpg","jpeg");
if($typeArr[0]== "image" && in_array($typeArr[1], $imgType)){
$fullpath = 'upload/image/'.$ymd.'';
if(!is_dir($fullpath)){
mkdir($fullpath,0777,true);
}
$imgname = "img_".time().".".$typeArr[1];
$bol = move_uploaded_file($_FILES["tmp_name"], $fullpath.$imgname);
if($bol){
echo $fullpath.$imgname;
// $this -> ajaxReturn(array('code'=>200,'msg'=>"上传成功",'url'=>$fullpath.$imgname));
} else {
$this -> ajaxReturn(array('code'=>400,'msg'=>"上传失败"));
}
} else {
$this -> ajaxReturn(array('code'=>400,'msg'=>"没有图片,再检查一下吧!"));
}
} else {
$this -> ajaxReturn(array('code'=>400,'msg'=>'错误码'.$_FILES["error"]));
}
}
base64方式就是传过来的数据经过了base64编码
数据是这种感觉的
下面直接上后台代码
public function base64imgupload(){
$img = I('data');
$ary = $this -> base64imgsave($img);
$this -> ajaxReturn($ary);
}
//base64上传的图片储存到服务器本地
protected function base64imgsave($img){
$ymd = date("Ymd");
$basedir = 'upload/base64/'.$ymd.'';
$fullpath = $basedir;
if(!is_dir($fullpath)){
mkdir($fullpath,0777,true);
}
$types = empty($types)? array('jpg', 'gif', 'png', 'jpeg'):$types;
$img = str_replace(array('_','-'), array('/','+'), $img);
$b64img = substr($img, 0,100);
if(preg_match('/^(\s*image\/(\w+);base64,)/', $b64img, $matches)){//正则取出相关数据
$type = $matches[2];
if(!in_array($type, $types)){
return array('code'=>400,'info'=>'图片格式不正确,只支持 jpg、gif、png、jpeg哦!','url'=>'');
}
$img = str_replace($matches[1], '', $img);//得到图片编码
$img = base64_decode($img);//解码
$photo = '/'.md5(date('YmdHis').rand(1000, 9999)).'.'.$type;
file_put_contents($fullpath.$photo, $img);
$ary['code'] = 200;
$ary['info'] = '保存图片成功';
$ary['url'] = $basedir.$photo;
return $ary;
}
$ary['code'] = 400;
$ary['info'] = '请选择要上传的图片';
return $ary;
}