Blogger Information
Blog 8
fans 0
comment 1
visits 19388
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
利用formdata异步上传图片并预览图片
鑫仔的博客
Original
1050 people have browsed it

<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('提交失敗');
           }
       });

   }



<?php
$file = $_FILES['file'];//得到传输的数据
$Name = $file['name'];//得到文件名称

$type = strtolower(substr($Name,strrpos($Name,'.')+1));//得到文件类型。转为小写
$allow_type = array('jpg','jpeg','gif','png');//定义允许上传的类型
//判断文件类型是否允许上传
if(!in_array($type,$allow_type)){
   //如果不允许,直接停止
   return;
}
//判读是否通过http post上传
if(!is_uploaded_file($file['tmp_name'])){
   return;
}
$upload_path = "image/";//上传文件的存放路径
//开始移动文件到相应的文件夹
if(move_uploaded_file($file['tmp_name'],$upload_path.$file['name'])){
   $response['isSuccess'] = true;
   $response['photo'] = $upload_path.$file['name'];
}else{
   $response['isSuccess'] = false;
}

//$picture = $upload_path.$file['name'];
echo json_encode($response);

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post