博客列表 >PHP ajax无刷新上传图片

PHP ajax无刷新上传图片

Pengsir
Pengsir原创
2018年04月22日 23:43:27752浏览

html代码:

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery/jquery-3.2.1.min.js"></script>
    <style>
        fieldset{
            width: 80%;
            height: 600px;
            margin: auto;
            text-align: center;
            font-weight: bolder;
            font-size: 2em;
            color: black;
            background-color: #cccccc;

        }
        P{
            font-size: 1em;
            padding: 20px;
        }
        p>input{
            font-size: 1.1em;
            margin-left: 20px;
        }
        p >input:hover{
            color: orange;
            cursor: pointer;
        }
        p>label{
            background-color: red;
        }
        button{
            width: 200px;
            height: 70px;
            background-color: paleturquoise;
            font-size: 40px;
            color: slategray;
        }
        button >span{
            font-size: 1.1em;
        }
    </style>

</head>
<body>
<form  method="POST" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="500000000">
    <fieldset>
        <legend>上传文件</legend>
        <p>
            <label for="upload">上传文件</label><input type="file" name="upload" id="upload">
        </p>
        <p align="center">
            <button type="submit" name="submit" id="submit">上传</button>
        </p>
    </fieldset>
</form>
<script>
        $('#submit').click(function () {
//            1.获取文件对象
            var file_data=$('#upload')[0].files[0]
            //2.上传文件类型时要用FormData类
            var formData = new FormData()
            //3.添加文件对象
            formData.append('upload',file_data)

            //ajax处理事件
            $.ajax({
                url:'uploadPic.php',
                type:'POST',
                data:formData,
                /**
                 * 必须false才会避开jQuery对 formdata 的默认处理
                 * XMLHttpRequest会对 formdata 进行正确的处理
                 */
                processData: false,
                /**
                 *必须false才会自动加上正确的Content-Type 用于对data参数进行序列化处理 这里必须false
                 */
                contentType: false,
                dataType:'json',
                cache:false,//上传文件无需缓存
                success: function (data) {
                    //数据状态为0  上传成功
                    if (data.status == 0) {
                        $('p').find('span').remove();
                        $('#submit').after('<span>').next().text(data.msg).css('color', 'green');
                    } else {
                        $('p').find('span').remove();
                        $('#submit').after('<span>').next().text(data.msg).css('color', 'red');
                    }
                }
            })
            return false
        })
</script>
</body>
</html>

运行实例 »

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

php代码(uploadPic.php):

实例

<?php
// 1.检测请求是否是post
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    //2.检查是否有文件被上传
    if (isset($_FILES['upload'])){
        // 3.允许文件上传的类型
        $allow=['image/jpg','image/jpeg','image/png'];
        //4.上传文件的类型在这个$allow中
        if (in_array($_FILES['upload']['type'],$allow)) {
            if (is_uploaded_file($_FILES['upload']['tmp_name'])){
                //5.将文件移动到临时目录
                if (move_uploaded_file($_FILES['upload']['tmp_name'],"pic/{$_FILES['upload']['name']}")) {
                    exit(json_encode(['status'=>0,'msg'=>'上传成功!']));
                }
            }
        } else {
            exit(json_encode(['status'=>1,'msg'=>'选择文件类型错误']));
        }
    }

    //对上传错误进行处理
    if ($_FILES['upload']['error']>0) {
        switch ($_FILES['upload']['error']) {
            case 1:
                exit(json_encode(['status'=>2,'msg'=>'文件超过了php.ini配置大小']));
                break;
            case 2:
                exit(json_encode(['status'=>3,'msg'=>'文件超过了html表单配置大小']));
                break;
            case 3:
                exit(json_encode(['status'=>4,'msg'=>'仅有部分文件上传']));
                break;
            case 4:
                exit(json_encode(['status'=>5,'msg'=>'没有文件上传']));
                break;
            case 6:
                exit(json_encode(['status'=>6,'msg'=>'没有可用的临时文件']));
                break;
            case 7:
                exit(json_encode(['status'=>7,'msg'=>'磁盘已满']));
                break;
            case 9:
                exit(json_encode(['status'=>8,'msg'=>'上传被终止!']));
                break;
            default:
                exit(json_encode(['status'=>9,'msg'=>'未知错误']));
                break;
        }

        //删除创建的临时文件,当然系统会自动清空
        if (file_exists($_FILES['upload']['tmp_name']) && is_file($_FILES['upload']['tmp_name'])){
            unlink($_FILES['upload']['tmp_name']);
        }
    }

} else {
    exit(json_encode(['status'=>10,'msg'=>'不是POST上传']));
}

运行实例 »

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

运行效果图:

ajax无刷新上传图片案例.png

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