博客列表 >4.19php+ajax实现文件验证并上传

4.19php+ajax实现文件验证并上传

吃不起土的少年的博客
吃不起土的少年的博客原创
2018年04月21日 19:32:17584浏览


实例


<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>上传照片</title>
	<style type="text/css">
	body{
		background-color:  #FFE4C4 ;
	}
	fieldset{

		width: 600px;
		margin: auto;
		margin-top: 200px;
		text-align: center;

	} 
	button{
		color: white;
		background-color: lightskyblue;
		border: none;
	}
	button:hover{
		background-color: orange;
	}
	.box{
		width: 400px;
		margin: auto;
		text-align: center;
	}
	#wrong{
		
        margin-left:auto;         
        margin-right:auto; 
    } 
    #pre{
    	margin: auto;
        margin-top: 10px;
    	display: block;
    	width: 120px;
    	height: 160px;

    }    
    img{
    	width: 120px;
    	height: 160px;
    }
    #reset{
    	margin-left: 20px;
    }
    </style>
</head> 
<body> 
<form action="" method="POST" enctype="multipart/form-data" target="form-target"> 
<input type="hidden" name="file_size" value="542488">
<fieldset>     
<legend>文件上传</legend>        
<p>请选择您要上传的文件:<input type="file" name="file" id="file" onchange="preview(this)"><span id="pre">
<img src="" id="pic" alt=""></span></p>

        
       <p><button type="submit">上传文件</button><button id="reset">Reset</button></p>

       <p><span id="res"></span>
	</fieldset>
	</form>
	<iframe style="width:0; height:0; border:0;" name="form-target" id="iframe"></iframe> 
	
<script type="text/javascript" src="../jQuery/jquery-3.3.1.js"></script>
	<script type="text/javascript">
	function preview(obj){
		//给上传文件添加一个预览效果
		$('#pic').attr('src',window.URL.createObjectURL(obj.files[0]))
        	// var img = $('#pic');  
         //        img.src = window.URL.createObjectURL(obj.files[0]);  

        	}
        	//添加一个重置 清空已经输入的file值
    $('#reset').on('click',function(){
    	var file = $("#file") 
        file.after(file.clone().val("")); 
        file.remove();
        $('#pic').removeAttr('src');
         $('#res').next().remove(); 
    })
	$(':button').first().on('click',function(){
		//

		var formData = new FormData($('form')[0]);
        formData.append('file',$(':file')[0].files[0]);

        $.ajax({
        	url:'check.php',
            type: 'POST',
            data: formData,
            dataType:'json',
            //这两个设置项必填
             contentType: false,
             processData: false,
             success: function(data){
             console.log(data)
            switch(data.status){
      	    	case 0:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"green","font-size":"0.8em"});
      	    	break;
      	    	case 1:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
      	    	case 2:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
      	    	case 3:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
      	    	case 4:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
      	    	case 5:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
      	    	case 6:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
      	    	case 7:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
      	    	case 8:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
      	    	case 9:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
      	    	case 10:
            	 console.log(data)
            	$('#res').next().remove()
      	    	$('#res').after('<span>').next().text(data.msg).css({"color":"red","font-size":"0.8em"});
      	    	break;
            }

     
  }       })
        
        })



      	    // 	switch(text){
      	    // 		case 0:
      	    // 		$('#res').next().remove()
      	    // 		$('#res').after('<span>').next().text(data.msg).css(
      	    // 			{"color":"red","font-size":"0.8em","font-style":"italic"});//.prev().focus();
      	    // 		break;
      	    // 	}
      	    // }


	
	</script>
	</body>
</html>



运行实例 »

点击 "运行实例" 按钮查看在线实例

实例

<?php 
	//先判断文件传输方式是否为POST
	if ($_SERVER['REQUEST_METHOD']=='POST') {
		//判断用户是否上传
		if(isset($_FILES['file'])){
			//设置用户可上传的文件类型
			$allow=['image/jpg','image/jpeg','image/png'];
			if (in_array($_FILES['file']['type'],$allow)) {

				if(move_uploaded_file($_FILES['file']['tmp_name'],"file/{$_FILES['file']['name']}")){
					// echo "1";
					exit(json_encode(['status'=>0,'msg'=>'上传成功']));
			}

	}else {          

		             // echo"2";
					//提示格式不对
					exit(json_encode(['status'=>2,'msg'=>'仅允许上传jpg和png格式的图片']));
				}

			}else{
		 exit(json_encode(['status'=>6,'msg'=>'没有文件被上传']));
		
		}

		//对上传错误进行处理
		if ($_FILES['file']['error'] > 0 ) {
			echo '<div class="box">';
			echo '<p id="wrong">错误原因是:<strong>';

			switch ($_FILES['file']['error']) {
				case 1:
				 // echo "3";
					exit(json_encode(['status'=>3,'msg'=>'文件超过了php.ini配置中设置的大小']));
					break;
				case 2:
				// echo "4";
					exit(json_encode(['status'=>4,'msg'=>'文件超过表单中设置的常量大小']));
					break;
				case 3:
				// echo "5";
					exit(json_encode(['status'=>5,'msg'=>'仅有部分文件上传']));
					break;
				case 4:
				// echo "6";
					exit(json_encode(['status'=>6,'msg'=>'没有文件被上传']));
					break;
				case 6:
				// echo "7";
					exit(json_encode(['status'=>7,'msg'=>'没有可用的临时文件夹']));
					break;
				case 7:
				// echo "8";
					exit(json_encode(['status'=>8,'msg'=>'磁盘已满,写入失败']));
					break;
				case 8:
				// echo "9";
					exit(json_encode(['status'=>9,'msg'=>'上传意外中止']));
					break;
				
				default:
					exit(json_encode(['status'=>10,'msg'=>'系统未知错误']));
					break;
			}
		
			//将创建的临时文件删除
			if (file_exists($_FILES['file']['tmp_name']) && is_file($_FILES['file']['tmp_name'])) {
				unlink($_FILES['file']['tmp_name']);
			}
		}
}		

运行实例 »

点击 "运行实例" 按钮查看在线实例

选择照片并上传微信图片_20180421192753.png

 此时上传的预设文件夹目录里面文件为空微信图片_20180421192742.png

开始上传图片

微信图片_20180421192756.png

上传成功

微信图片_20180421192800.png

此时目录里面有了上传的照片

微信图片_20180421192803.png

点击重置按钮 

微信图片_20180421192807.png

上传一个错误类型文件

微信图片_20180421192812.png

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议