优化文件上传

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.11.3.min.js"></script>

    <title>多文件带进度条上传</title>

    <style type="text/css">

        *{

            font-family: 'microsoft yahei';

            color: #4A4A4A;

        }

        .upload{

            width: 750px;

            padding: 15px;

            border: 1px dashed #ccc;

            margin: 25px auto;

            border-radius: 5px;

        }    

        .uploadBox{

            width: 100%;

            height: 35px;

            /*background: #F0F0F0;*/

            position: relative;

        }

        .uploadBox input{

            height: 30px;

            background: red;

            position: absolute;

            top: 2px;

            left: 0;

            z-index: 201;

            opacity: 0;

            cursor: pointer;

        }

        .uploadBox .inputCover{

            width: 100px;

            height: 30px;

            position: absolute;

            top: 2px;

            left: 0;

            z-index: 200;

            text-align: center;

            line-height: 30px;

            font-size: 14px;

            border: 1px solid #009393;

            border-radius: 5px;

            cursor: pointer;

        }

        .uploadButton{

            width: 100px;

            height: 30px;

            position: absolute;

            left: 65%;

            border-radius: 5px;

            border: 1px solid #ccc;

            background: #F0F0F0;

            outline: none;

            cursor: pointer;

        }

        .uploadButton:hover{

            background: #E0E0E0;

        }

        .processBar{

            display: inline-block;

            width: 0;

            height: 7px;

            position: absolute;

            left: 600px;

            top: 14px;

            background: #009393;

        }

        .processNum{

            position: absolute;

            left: 650px;

            color: #009393;

            font-size: 12px;

            line-height: 35px;

        }

        .delFile{

            width:40px;

            position: absolute;

            left: 715px;

            color: red;

            font-size: 12px;

            height:30px;

            line-height: 30px;

            border-radius: 5px;

            text-align: center;

            border: 1px solid red;

            cursor:pointer;

        }

        .show{

            text-align: center;

            font-size: 14px;

            color: #4A4A4A;

        }

        .fileInfo{

            min-width: 200px;

            height: 30px;

            position: absolute;

            top: 2px;

            margin-left:150px;

            text-align: center;

            line-height: 30px;

            font-size: 14px;

            border-radius: 5px;

        }

        .cancelFile{

            width: 50px;

            height: 30px;

            position: absolute;

            top: 2px;

            margin-left:500px;

            text-align: center;

            line-height: 30px;

            font-size: 14px;

            border: 1px solid red;

            color:red;

            border-radius: 5px;

            text-decoration:none;

            display:none;

        }

        .addFile{

            width: 80px;

            height: 30px;

            position: relative;

            margin-bottom:15px;

            left: 66%;

            border-radius: 5px;

            border: 1px solid #afdfd0;

            text-align: center;

            line-height:30px;

            color:#00bb80;

            background: #e8f8f3;

            font-size:14px;

            cursor:pointer;

        }

    </style>

</head>

<body>

    <div class="addFile">添加文件</div>

    <div class="upload">

        <div class="uploadBox">

            <span class="inputCover">选择文件</span>

            <span class="fileInfo"></span>

            <a href="javascript:void(0);" class="cancelFile">取消</a>

            <form enctype="">

                <input type="file" name="file" class="file"/>

            </form>

            <span class="processBar"></span>

            <span class="processNum">未选择文件</span>

        </div>

    </div>

    <button type="button" class="uploadButton">上传</button>

    <div class="show"></div>

</body>

<script>

$(document).ready(function(){

    var num = 0;

    var uploadNum = 0;

    var errorInfo = '';

    var filetypes =["jpg", "png", "gif", "jpeg", "mp3", "flv", "avi", "mp4", "doc", "docx", "txt", "xlsx", "xls", "ppt", "pptx", "pdf", "wgt"];

    //选择文件时,相关事件

    $(document).on('change','input[type=file]',function(){

        var filemaxsize = 1024*1024*1024;//1G,最大上传限制

        var isIE = /msie/i.test(navigator.userAgent);//判断是否是ie浏览器

        var fileSize = 0;

        var filePath=$(this).val();

        if (isIE && !this.files) {

            var filePath = this.value;

            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");

            if(!fileSystem.FileExists(filePath)){

                alert("附件不存在,请重新选择!");

                return false;

            }

            var file = fileSystem.GetFile (filePath);

            fileSize = file.Size;

        } else {

            if(this.files.length > 0){

                fileSize = this.files[0].size;

            }else{

                return false;

            }

        }

        //判断文件类型

        var isnext = false;

        var fileEnd = filePath.substring(filePath.indexOf(".")+1).toLowerCase();

        for(var i =0; i<filetypes.length;i++){

          if(filetypes[i]==fileEnd){

              isnext = true;

              break;

          }

        }

        if(!isnext){

          alert("您未上传文件,或者您上传文件类型有误!");

          return false;

        }

        if(fileSize > filemaxsize){

            inputCover.html("<font>文件大于1G,请重新选择</font>");

            processNum.html('未选择文件');

            filePath = '';

            return false;

        }else{

            $(this).parent().parent().find('.inputCover').html('重新选择');

            $(this).parent().parent().find('.fileInfo').html(this.files[0].name+' / '+parseInt(fileSize/1024)+'KB');

            $(this).parent().parent().find('.cancelFile').show();

            $(this).parent().parent().find('.processNum').html('等待上传');

        }

    });


    //取消文件事件

    $(document).on('click','.cancelFile',function(){

        $(this).parent().find('.file').val(null); 

        $(this).parent().find('.inputCover').html('选择文件');

        $(this).parent().find('.fileInfo').html('');

        $(this).parent().find('.cancelFile').hide();

        $(this).parent().find('.processNum').html('未选择文件');

    });


    //新增文件事件

    $(document).on('click','.addFile',function(){

        if(num > 3){

            alert('最多上传5个文件');

            return false;

        }

        var html = '';

        html += '<div class="uploadBox">';

        html += '<span class="inputCover">选择文件</span>';

        html += '<span class="fileInfo"></span>';

        html += '<a href="javascript:void(0);" class="cancelFile">取消</a>';

        html += '<form enctype="">';

        html += '<input type="file" name="file" class="file"/>';

        html += '</form>';

        html += '<span class="processBar"></span>';

        html += '<span class="processNum">未选择文件</span>';

        html += '<span class="delFile">删除</span>';

        html += '</div>';

        $('.upload').append(html);

        num++;

    });


    //删除文件事件

    $(document).on('click','.delFile',function(){

        $(this).parent().remove();

        num--;

    });


    $(document).on('click','.uploadButton',function(){

        upload();

    })

    //创建ajax对象,发送上传请求

    function upload(){

        //由于在success中用了延迟,导致当num<0时会再次执行upload函数

        if(num < 0){

            return false;

        }

        var paramData = new FormData();

        var filesInfo = $(".upload").children('.uploadBox').eq(uploadNum).find('.file')[0].files;

        if(filesInfo.length == 0){

            paramData.append('Filedata','');

        }else{

            paramData.append('Filedata',filesInfo[0]);

        }

        $.ajax({

            type: "post",

            url:'upload.php',

            data:paramData,

            cache:false,

            async:true,

            processData: false,

            contentType: false,

            xhr:function(){

                var myXhr = $.ajaxSettings.xhr();

                if(myXhr.upload){

                    myXhr.upload.addEventListener('progress',function(e){                

                        var loaded = e.loaded;

                        var total = e.total;

                        var percent = Math.floor(100*loaded/total);

                        if(percent == 100){

                            percent = 99;

                        }

                        if(filesInfo.length != 0){

                            $(".upload").children('.uploadBox').eq(uploadNum).find('.processNum').html(percent+"%");

                            $(".upload").children('.uploadBox').eq(uploadNum).find('.processBar').css("width",(percent/2)+"px");

                        }


                    }, false);

                }

                return myXhr;

            },

            success: function(data){

                if(data.code == 1){

                    $(".upload").children('.uploadBox').eq(uploadNum).find('.processNum').html("100%");

                    $(".upload").children('.uploadBox').eq(uploadNum).find('.processBar').css("width","50px");

                }else{

                    errorInfo += '第'+(uploadNum+1)+'个'+data.msg+"\n";

                }

                uploadNum++;

                num--;

                if(num < 0){

                    if(errorInfo != ''){

                        //延迟200ms执行,等渲染完成

                        window.setTimeout(function () {

                            alert(errorInfo);

                            location.reload();

                            return false;

                        }, 200);

                    }else{

                        //延迟200ms执行,等渲染完成

                        window.setTimeout(function () {

                            alert('全部上传成功!');

                            location.reload();

                            return false;

                        }, 200);

                    }

                }

                upload();

            }

        })

    }

})

</script>

</html>

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335