Blogger Information
Blog 46
fans 3
comment 2
visits 39480
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP文件上传(用Ajax方式显示信息) 2018年4月19日
墨雨的博客
Original
574 people have browsed it

用系统变量$_FILES判断用户输入的合法性,用move_uploaded_file()函数实现文件上传,用$.ajax()的success参数的回调函数收集反馈信息。

1、用户输入表单代码(m.php):

实例

<meta charset="UTF-8">
<!-- $_SERVER['PHP_SELF']:当前php脚本 -->
<!-- enctype="multipart/form-data" :允许通过表单上传文件-->
<!-- method:请求类型必须是POST -->
<form enctype="multipart/form-data" id="upload">
	<!-- 用隐藏域设置允许上传的文件大小,仅考参考 -->
	<input type="hidden" name="MAX_FILE_SIZE" value="542488">
	<fieldset>
		<legend>图片上传</legend>
		<p>选择文件:<input type="file" name="img" id="img"></p>
		<span style="color: #f00"></span>
		<p align="center"><button>上传</button></p>
	</fieldset>	
</form>

<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">

    $('button').click(function(){
        var formData=new FormData();
        var files=document.getElementById('img');
        var file=files.files[0];

        formData.append('img',file);
        $.ajax({
            url:'admin.php',
            type:'POST',
            data:formData,
            processData : false,
            contentType : false,
            success:function(data){
                $('span').text(data);
            }
        });
        return false;
    })
</script>

运行实例 »

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

2、后台处理代码(upload.php):

实例

<?php
header("content-type:text/html;charset=utf-8");
//检测请求类型是否POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    //检测是否有文件被上传
    if (!empty($_FILES['img']['name'])) {
        //设置允许上传的文件类型
        $allow = ['image/jpg','image/jpeg', 'image/png'];
        if (in_array($_FILES['img']['type'], $allow)) {
            //将文件先移动到临时目录
            move_uploaded_file($_FILES['img']['tmp_name'], "upload/{$_FILES['img']['name']}");
        }else {
            //提示格式不对
            exit('只允许上传jpg和png格式的图片');
        }
    } else {
        exit('你还未选择文件!');
    }
    //对上传错误进行处理
    if ($_FILES['img']['error'] > 0 ) {
        //上传失败
        exit('文件上传失败!');
    } else {
        //上传成功
        exit('文件上传成功!');
    }
}

运行实例 »

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



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