PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传

汉王 PHP+MySQL 收藏

上传表单

<form class="imageform" method="post" enctype="multipart/form-data" action="upload.php"> 
    <div class="up_status" style="display:none"><img src="loader.gif" alt="uploading"/></div> 
    <div  class="btn up_btn"> 
        <span>添加图片</span> 
        <input class="photoimg" type="file" name="photoimg"> 
    </div> 
</form> 
<div class="preview_img"></div>
引入样式和上传插件jquery.wallform.js
<link rel="stylesheet" type="text/css" href="css/style.css" /> 
<script type="text/javascript" src="jquery.min.js"></script> 
<script type="text/javascript" src="jquery.wallform.js"></script>
jQuery
$("body").on("change", ".photoimg", 
function() { 
    var obj = $(this); 
    var imageForm = obj.parents(".imageform"); 
    var preview_img = imageForm.next(".preview_img"); 
    var btn = imageForm.find(".up_btn"); 
 
    imageForm.ajaxForm({ 
        target: preview_img, 
        beforeSubmit: function() { 
            imageForm.next("div.preview_img").html(""); 
            preview_img.hide(); 
            btn.hide(); 
        }, 
        success: function() { 
            preview_img.show(); 
            btn.show(); 
        }, 
        error: function() { 
            btn.show(); 
            preview_img.hide(); 
        } 
    }).submit(); 
});
PHP上传 upload.php
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { 
    $name = $_FILES['photoimg']['name']; 
    $size = $_FILES['photoimg']['size']; 
 
    if (empty($name)) { 
        echo '请选择要上传的图片'; 
        exit; 
    } 
    $ext = extend($name); 
    if (!in_array($ext, $extArr)) { 
        echo '图片格式错误!'; 
        exit; 
    } 
    if ($size > (1000 * 1024)) { 
        echo '图片大小不能超过1M'; 
        exit; 
    } 
    $image_name = time() . rand(100, 999) . "." . $ext; 
    $tmp = $_FILES['photoimg']['tmp_name']; 
    if (move_uploaded_file($tmp, $path . $image_name)) { 
        echo '<img src="' . $path . $image_name . '"  class="preview">'; 
    } else { 
        echo '上传出错了!'; 
    } 
    exit; 
}

PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传

下载地址