Blogger Information
Blog 27
fans 1
comment 2
visits 25248
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
采用AJax方式实现一个文件上传的过程(2018年4月20日18时39分)
一枝黄花
Original
766 people have browsed it

代码实现效果:当点击文件上传 的时候,上传的文件自动会到临时文件夹upload文件夹下面。

微信截图_20180420183748.png

代码如下:

实例

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" enctype="multipart/form-data">
	<!-- 用隐藏域设置允许上传的文件大小,仅考参考 -->
	<input type="hidden" name="MAX_FILE_SIZE" value="542488">
	<fieldset>
		<legend align="center">文件上传</legend>
		<p><strong>选择文件:</strong><input type="file" name="upload"></p>
	</fieldset>	
	<p align="center"><button type="submit" name="submit" >上传</button></p>
</form>

<?php 
	//检测请求类型是否POST,如果不是应该提示用户类型不对
	if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		//检测是否有文件被上传
		if (isset($_FILES['upload'])) {
			//设置允许上传的文件类型
			$allow = ['image/jpg','image/jpeg', 'image/png'];
			if (in_array($_FILES['upload']['type'], $allow)) {
				//将文件先移动到临时目录
				if (move_uploaded_file($_FILES['upload']['tmp_name'], "upload/{$_FILES['upload']['name']}")){
					//上传成功
					echo "<script>alert('文件上传成功')</script>";
				} 
			}else {
					//提示格式不对
					echo "<script>alert('仅允许上传jpg和png格式的图片')</script>";
				}
		}
		

			echo '</strong></p>';
			//保险起见,最好把创建的临时文件删除,当然系统也会在结束会话时自动清空
			if (file_exists($_FILES['upload']['tmp_name']) && is_file($_FILES['upload']['tmp_name'])) {
				unlink($_FILES['upload']['tmp_name']);
			}
	
	} else {
		echo '1';
	}
?>

运行实例 »

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


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