Blogger Information
Blog 38
fans 0
comment 0
visits 29741
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JQUERY+AJAX无刷新校验并实现文件上传
riskcn的博客
Original
559 people have browsed it

总结:

  1. FormData(),大小写不要写错;难点,没学,网上也不好找详细用法,为什么file数据为数组形式?

  2. ajax提交方式要注意两个false量,不然出错;

  3. 处理脚本里面$_FILES['...']['...'],第一个方括号里面的内容是变量,一定要和前端传输数据对应,不要照抄,不然出错!!

index.php

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>0419,实战PHP文件上传</title>
</head>
<body>
	<form method="post" enctype="multipart/form-data">
		<fieldset>
			<legend>PHP文件上传</legend>
			<p>
				<label for="myfile"></label>
				<input type="file" name="file" id="file">
			</p>
			<p>
				<button type="submit" name="submit" id="submit">提交</button>
			</p>
		</fieldset>	
	</form>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
	//给按钮添加click事件
	$('#submit').on('click',function(){
		//选择input元素????一个input为什么是数组????
		var file= $('#file')[0];

		var files=file.files[0];
		 // console.log(files)
		 //创建FormData对象-----一个单词都不要写错,不然返回未定义
		var formdata= new FormData();
		// 给formdata后面添加获取到的信息
		formdata.append('files',files);

//使用$.ajax方式提交
		$.ajax({
			url:'check.php',
			type:'POST',
			data:formdata,
			processData : false,//重要,禁止序列化
			contentType : false,//重要,忽略数据类型
			success:function(res){
				$('span').empty()
				$('#submit').after('<span>').next().text(res);
			}
		})
		return false;//禁止跳转
	})

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

运行实例 »

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

check.php

实例

<?php 
header("Content-Type: text/html; charset=UTF-8");
if($_SERVER['REQUEST_METHOD']=='POST'){//检查提交方式,必须为post

	if(isset($_FILES['files'])){//检查是否存在
		$type=['image/jpg','image/jpeg','image/png'];
		if(in_array($_FILES['files']['type'], $type)){//检查文件类型
			if(move_uploaded_file($_FILES['files']['tmp_name'],'upload/'.$_FILES['files']['name'])){
				echo "上传成功";
			}
		}else{
			echo "上传文件类型错误";
			exit();
		}
	}else{
		echo "请上传文件!";
		exit();
	}
	if($_FILES['files']['error']>0){//返回错误
		echo "上传错误!";
		exit();
	}
	//清空缓存
	if(file_exists($_FILES['files']['tmp_name'])&&is_file($_FILES['files']['tmp_name'])){
			unlink($_FILES['files']['tmp_name']);
		}
}

运行实例 »

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

运行效果:

QQ截图20180423143003.png

QQ截图20180423143052.png


Correction status:Uncorrected

Teacher's comments:
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