利用formdata异步上传图片并预览图片

<img src="" style="width: 120px;margin-bottom: 5px" id="previewimg0">
<form action="" enctype="multipart/form-data" id="form0">
   <input type="file"  name="file" id="file0" onChange="preview(this,0)" style="width: 70px;margin-left: 25px">
</form>
function preview(obj,id){
       var img = document.getElementById("previewimg"+id);
       img.src = window.URL.createObjectURL(obj.files[0]);
       var data = new FormData($('#form'+id)[0]);
       $.ajax({
           url: 'uploadoption.php',
           type: 'POST',
           data: data,
           dataType: 'JSON',
           cache: false,
           processData: false,
           contentType: false
       }).done(function(ret){
           if(ret['isSuccess']){
               img.src = window.URL.createObjectURL(obj.files[0]);
           }else{
               alert('提交失敗');
           }
       });

   }
 1 <?php
 2 $file = $_FILES['file'];//得到传输的数据
 3 $Name = $file['name'];//得到文件名称
 4 
 5 $type = strtolower(substr($Name,strrpos($Name,'.')+1));//得到文件类型。转为小写
 6 $allow_type = array('jpg','jpeg','gif','png');//定义允许上传的类型
 7 //判断文件类型是否允许上传
 8 if(!in_array($type,$allow_type)){
 9    //如果不允许,直接停止
10    return;
11 }
12 //判读是否通过http post上传
13 if(!is_uploaded_file($file['tmp_name'])){
14    return;
15 }
16 $upload_path = "image/";//上传文件的存放路径
17 //开始移动文件到相应的文件夹
18 if(move_uploaded_file($file['tmp_name'],$upload_path.$file['name'])){
19    $response['isSuccess'] = true;
20    $response['photo'] = $upload_path.$file['name'];
21 }else{
22    $response['isSuccess'] = false;
23 }
24 
25 //$picture = $upload_path.$file['name'];
26 echo json_encode($response);

猜你喜欢

转载自www.cnblogs.com/jierong12/p/10245885.html
今日推荐