header("Content-Type: text/html; charset=utf-8"); /*print_r($_FILES)*/;//所有传入的图片都在files这个数组里 //得到文件对象 $base64_image_content = $_POST['img']; $addName=$_SESSION['username']; //匹配出图片的格式 if (preg_match('/^(data:s*image/(w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; print_r($result); $new_file = "../usersIMG/"; if(!file_exists($new_file)) { //检查是否有该文件夹,如果没有就创建,并给予最高权限 mkdir($new_file, 0700); } $new_file = $new_file.$addName.".{$type}"; //解码图片 if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){ $conn=mysqli_connect(MYSQL_HOST,MYSQL_USER,MYSQL_PW,dbname); //防止传入数据库里的中文乱码 mysqli_query($conn,"SET names UTF8"); $sql="update users set img='$new_file' where username='$addName'"; $query=mysqli_query($conn,$sql); if($query){ $_SESSION['img']=$new_file; echo '保存成功'; }else { echo json_encode(0); } }else{ echo '保存失败'; } }