【Ajax】ajax上传文件及进度条的实现

    html5上传是同步上传的方式,所以能够实现进度条的显示。
    1.上传文件:
    首先我们用ajax来取得<input type="file" id="file_upload">的file对象:
    
    var file = null;
    var input = $("#file_upload");
    //文件域选择文件时, 执行readFile函数
    input.addEventListener('change',readFile,false);
    function readFile(){ 
        file = this.files[0]; 
    }

    然后用FormData()送到后台。
    
var fd = new FormData();
fd.append("file", file);

    2.监听事件:给XMLHttpRequest添加上传中的监听事件,可以得到已上传的文件大小,用以实现进度条的显示。
    
 //监听事件
xhr.upload.addEventListener("progress", uploadProgress, false);

    完整代码如下:
<html>
<head>
<meta charset="utf-8">
<title>进度条测试</title>
<script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
</head>
<body>

    <input type="file" id="file_upload"/>
    <input type="button" value="上传" id="upload"/>
    <div style="background:#848484;width:100px;height:10px;margin-top:5px">
        <div id="progressNumber" style="background:#428bca;width:0px;height:10px" >
        </div>    
    </div>
    <font id="percent">0%</font>
</body>
<script>
var file = null;
$(function(){
    $("#upload").click(function(){
        upload();
    });
});
var input = document.getElementById("file_upload");

//文件域选择文件时, 执行readFile函数
input.addEventListener('change',readFile,false);

function readFile(){ 
    file = this.files[0]; 
}
//上传文件
function upload(){
        var xhr = new XMLHttpRequest();

        var fd = new FormData();

        fd.append("fileName", file);

        //监听事件
        xhr.upload.addEventListener("progress", uploadProgress, false);

        //发送文件和表单自定义参数
        xhr.open("POST", "../UploadServlet",true);

        xhr.send(fd);
    }

    function uploadProgress(evt){
        if (evt.lengthComputable) {                  
            //evt.loaded:文件上传的大小   evt.total:文件总的大小                    
            var percentComplete = Math.round((evt.loaded) * 100 / evt.total);    
            //加载进度条,同时显示信息          
            $("#percent").html(percentComplete + '%')
            $("#progressNumber").css("width",""+percentComplete+"px");             
        }
    }
</script>
</html>
    效果如下:



Author:立礼
Sign:人生不要有太多的幻想,而要有更多的行动
    
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值