PHP + jQuery实现ajax文件即时上传 预览

来源:互联网 发布:身份证识别仪破解软件 编辑:程序博客网 时间:2024/04/29 12:54

参考:http://www.helloweba.com/view-blog-189.html


<!--test.html--><style type="text/css">    .demo{width:620px; margin: 15px 165px;}    .demo p{line-height:32px}    .btn{position: relative;overflow: hidden;margin-right: 4px;display:inline-block;*display:inline;padding:4px 10px 4px;font-size:14px;line-height:18px;*line-height:20px;color:#fff;text-align:center;vertical-align:middle;cursor:pointer;background-color:#5bb75b;border:1px solid #cccccc;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}    .btn input {position: absolute;top: 0; right: 0;margin: 0;border: solid transparent;opacity: 0;filter:alpha(opacity=0); cursor: pointer;}    .progress { position:relative; margin-left:100px; margin-top:-24px; width:200px;padding: 1px; border-radius:3px; display:none}    .bar {background-color: green; display:block; width:0%; height:20px; border-radius: 3px; }    .percent { position:absolute; height:20px; display:inline-block; top:3px; left:2%; color:#fff }    .files{height:22px; line-height:22px; margin:10px 0}    .delimg{margin-left:20px; color:#090; cursor:pointer}</style><script src="../drivers/jquery-1.4.1.js" type="text/javascript"></script><script type="text/javascript" src="../drivers/jquery.form.js"></script><script type="text/javascript" src="../drivers/tongji.js"></script><div class="demo">    <input type="file" style="display:none;"><br/>    <p>说明:支持xx/xx/xx格式图片</p><!--支持的图片格式,自定义-->    <div class="btn">        <span>选择封面</span>        <input id="fileupload" type="file" name="mypic">    </div>    <div class="progress">        <span class="bar"></span><span class="percent">0%</span >    </div>    <div class="files"></div>    <div id="showimg">        <?php        echo $sava_img;        ?>    </div></div><script type="text/javascript">    $(function() {        var bar = $('.bar');        var percent = $('.percent');        var showimg = $('#showimg');        var progress = $(".progress");        var files = $(".files");        var btn = $(".btn span");        $("#fileupload").wrap("<form id='myupload' action='test.php' method='post' enctype='multipart/form-data'></form>");        $("#fileupload").live('change', function() {//$("#fileupload").change(function() {            var filePath = document.getElementById('fileupload').value;            if (filePath == "") {                return;            }            var timeStr = "&time=" + new Date().getTime();            //alert(timeStr);            document.getElementById("myupload").action = "test.php?img_path=" + timeStr;            $("#myupload").ajaxSubmit({                dataType: 'json',                beforeSend: function() {                    showimg.empty();                    progress.show();                    var percentVal = '0%';                    bar.width(percentVal);                    percent.html(percentVal);                    btn.html("上传中...");                },                uploadProgress: function(event, position, total, percentComplete) {                    var percentVal = percentComplete + '%';                    bar.width(percentVal);                    percent.html(percentVal);                },                success: function(data) {                    files.html("<b>" + data.name + "(" + data.size + "k)</b> <span class='delimg' rel='" + data.pic + "'>删除</span>");                    var img = "" + data.pic;                    showimg.html("<img width='222px' height='125px' src='" + img + "'>");                    btn.html("重新选择");                    document.getElementById('fileupload').value = ''; //                    document.getElementById('img_src').value = img;                },                error: function(xhr) {                    btn.html("上传失败");                    bar.width('0')                    files.html(xhr.responseText);                    document.getElementById('fileupload').value = '';                }            });        });        $(".delimg").live('click', function() {            var pic = $(this).attr("rel");            $.post("test.php?act=delimg", {imagename: pic}, function(msg) {                if (msg == 1) {                    files.html("删除成功.");                    showimg.empty();                    progress.hide();                    document.getElementById('img_src').value = "";                } else {                    alert(msg);                }            });        });    });</script>

<?php/* * test.php */$action = $_GET['act'];if ($action == 'delimg') {    $filename = $_POST['imagename'];    $delPath = $_SERVER['DOCUMENT_ROOT'] . $filename;    if (!empty($delPath)) {        unlink($delPath);        echo '1';    } else {        echo '删除失败.';    }} else {    $picname = $_FILES['mypic']['name'];    $picsize = $_FILES['mypic']['size'];    if ($picname != "") {        if ($picsize > 1024000) {            echo '图片大小不能超过1M';            exit;        }        $type = strstr($picname, '.');        $type = strtolower($type);        if ($type != ".gif" && $type != ".jpg" && $type != ".png") {            echo '图片格式不对!';            exit;        }        //上传路径        $rootPath = $_SERVER['DOCUMENT_ROOT'];        list($usec, $sec) = explode(".", microtime());        $haoMiao = (float) $sec; //毫秒        $target_path = '/img/test/' . date("/Y/m/d/His_") . $haoMiao . "_orgtemp." . get_extname($_FILES['mypic']['name']);        creDir($rootPath . $target_path);        if (!empty($_FILES['mypic']['tmp_name'])) {            move_uploaded_file($_FILES['mypic']['tmp_name'], $rootPath . $target_path);        } else {            $target_path = '';            msg("上传图片失败!");        }    }    $size = round($picsize / 1024, 2);    $arr = array(        'name' => $picname,        'pic' => $target_path, //$pics,        'size' => $size    );    echo json_encode($arr);}// 获得扩展名函数function get_extname($fname) {    $temp = explode(".", $fname);    $where = count($temp) - 1;    return $temp[$where];}//创建一个新的文件夹function creDir($newPath) {    $temp = explode('/', $newPath);    $p = '';    $result = true;    $len = count($temp);    if (!(strpos($temp[$len - 1], '.') === false)) {        array_pop($temp);    }    foreach ($temp as $value) {        $p.=$value . '/';        if (!is_dir($p))            $result = $result && @mkdir($p);    }    return $result;}



当然、有借鉴其他人的地方、感恩···有不同意见的、请发表下···欢迎批评···求交流···O(∩_∩)O


与本文章配套的js文件的下载地址:


http://download.csdn.net/detail/zh89233/8437503


0 0
原创粉丝点击