原理:
1.使用FileReader 读取图片的base64编码
2.使用ajax,把图片的base64编码post到服务器。
3.根据接收到post的数据分析图片的类型(jpg,gif,png),并把base64_decode后的数据生成对应类型的图片文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>use the fileReader to get load the picture</title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
window.οnlοad=function(){
document.getElementById('img').οnchange=function(){
var img=event.target.files[0];
if(!img){
return;
}
if(!(img.type.indexOf('image')==0&&img.type&&/\.(?:jpg|png|gif)$//test(img.name))){
alert('please selct the image in type of jpg or png or gif');
return;
}
var reader=new FileReader();
reader.οnlοad=function(e){
$.post("servse.php",{img:e.target.reslut},function(ret){
if(!ret.img!=''){
alert('upload success');
$('#image').html('<img src="'+ret.img+'">');
}
},'json');
}
}
</script>
</head>
<body>
<section>
<input type="file" class="file" id="img"><label class="filebtn" for="img" title="JPG,GIF,PNG">Select</label>
<div class="image" id="image"></div>
</section>
</body>
</html>
<?php
$img=isset($_POST['img'])?_POST['img']:'';
list($type,$data)=explode(',',$img);
if(strstr($type,'image/jpeg')!==''){
$ext='.jpg';
}else if(strstr($type,'image/gif')!==''){
$ext='.png';
}
$photo=time().$ext;
file_put_contents($photo,base64_decode($data),true);
header("content-type:application/json";charset="utf-8");
$ret=array('img'=>$photo);
echo json_encode($ret);
?>