1、前端html页面
<div class="weui-uploader">
<div class="weui-uploader__hd">
<p class="weui-uploader__title">照片:</p>
</div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files yiwu">
</ul>
<div class="weui-uploader__input-box xiyipic">
<input id="file" class="weui-uploader__input" type="file" accept="image/*" capture="camera">//自动调用相机功能
</div>
</div>
</div>
$("#file").on("change",function(){
var _this = $(this)[0];
var _file = _this.files[0];
var fileType = _file.type;
var fileSize = _file.size;
var maxSize = 5*1024*1024;
//上传大小判断
if(fileSize > maxSize){
$.toast('上传图片超出允许上传大小', "cancel");
return false;
}
$.showLoading('正在上传');
if(/image\/\w+/.test(fileType)){
var fileReader = new FileReader();
fileReader.readAsDataURL(_file);
fileReader.onload = function(event){
var result = event.target.result; //返回的dataURL
var image = new Image();
image.src = result;
image.onload = function(){ //创建一个image对象,给canvas绘制使用
var cvs = document.createElement('canvas');
var scale = 1;
if(this.width > 1000 || this.height > 1000){
if(this.width > this.height){
scale = 1000 / this.width;
}else{
scale = 1000 / this.height;
}
}
cvs.width = this.width*scale;
cvs.height = this.height*scale; //计算等比缩小后图片宽高
var ctx = cvs.getContext('2d');
ctx.drawImage(this, 0, 0, cvs.width, cvs.height);
var newImageData = cvs.toDataURL('image/jpeg', 0.7);
var sendData = newImageData.replace('data:base64', 'data:image/jpeg;base64');
$.ajax({
url: '__CONTROLLER__/yiwuPic',
type: 'POST',
dataType: 'json',
data: {img: sendData},
success:function(data){
if(data.code == 1){
$.hideLoading();
//上传成功后自动动创建img标签放在指定位置
var img =$('<li class="weui-uploader__file" style="background-image:url('+data.img.substring(1)+')"></li>');
$(".yiwu").append(img);
$(".xiyipic").append('<input type="hidden" name="xiyipic[]" value="'+data.img.substring(1)+'"></input>');
}else{
$.toast('上传失败', "cancel");
}
}
});
}
}
}else{
$.toast('请选择图片格式文件', "cancel");
}
});
后台php处理
public function yiwuPic(){$post = $_POST['img'];//获取到的base64编码
$data = base64_decode(str_replace('data:image/jpeg;base64', '', $post));//替换
$time = date('Y-m-d');
$path = "./Public/Upload/".$time;
if(!file_exists($path)){
mkdir($path);//创建文件夹
}
$dst = $path.'/'.date('H-i-s').'.jpg';//目标路径
$a = file_put_contents($dst, $data);//将编码写入本地文件
if($a){
echo json_encode(array('code' => 1,'img' => $dst));die;
}else{
echo json_encode(array('code' => 0));die;
}
}