html部分
<form id="upload_form" enctype ="multipart/form-data">
<input type="file" style="display: none" id="upload_head">
</form>
jquery部分
$(document).on('click','#head',function(){
$('#upload_head').trigger('click');
});
$("#upload_head").change(function(){
var file = this.files[0];
if (window.FileReader) {
var reader = new FileReader();
// 图片文件转换为base64
reader.readAsDataURL(file);
reader.onload = function(){
let img = this.result;
$.ajax({
url : "#",
type : "POST",
data : {
img_base64:img,
},
dataType:"json",
success : function(data) {
if(data.status==1){
$("#head").attr("src",img);
}else{
$.toptip(data.info,'danger');
}
}
});
}
}
});
php部分
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base, $result)){
$type = $result[2];
$new_file = "public/avatar_uploads/".date('Ymd',time())."/";
if(!file_exists($new_file))
{
mkdir($new_file, 0700);
}
$str=rand(1000,9999);
$new_files = $new_file.date('Ymdhis',time()).$str.".{$type}";
if (file_put_contents($new_files, base64_decode(str_replace($result[1], '', $base)))){
//删除原路径图片
$prvImg=‘’;
if(!empty($prvImg)){
$prvImg='.'.$prvImg;
@unlink($prvImg);
}
$path="/".$new_files;
//存入数据库
}
}