jQuery文件上传进度条 [英] File upload progress bar with jQuery

查看:37
本文介绍了jQuery文件上传进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的项目中实现 AJAX 文件上传功能.我为此使用 jQuery;我的代码使用 AJAX 提交数据.我也想实现一个文件上传进度条.我怎样才能做到这一点?有什么方法可以计算已经上传了多少,以便我可以计算上传的百分比并创建进度条?

解决方案

注意:这个问题与jQuery 表单插件.如果您正在寻找纯 jQuery 解决方案,从这里开始.没有适用于所有浏览器的整体 jQuery 解决方案.所以你必须使用插件.我正在使用 dropzone.js,它对旧浏览器有一个简单的回退.您更喜欢哪个插件取决于您的需求.那里有很多很好的比较帖子.

来自示例:

jQuery:

$(function() {var bar = $('.bar');var 百分比 = $('.percent');var status = $('#status');$('form').ajaxForm({发送前:函数(){状态.空();var percentVal = '0%';bar.width(percentVal);百分比.html(percentVal);},上传进度:功能(事件,位置,总计,百分比完成){var percentVal = percentComplete + '%';bar.width(percentVal);百分比.html(percentVal);},完成:功能(xhr){status.html(xhr.responseText);}});});

html:

<input type="file" name="myfile"><br><input type="submit" value="上传文件到服务器"></表单><div class="progress"><div class="bar"></div ><div class="percent">0%</div >

<div id="状态"></div>

你必须用 css 设置进度条的样式...

I am trying to implement an AJAX file upload feature in my project. I am using jQuery for this; my code submits the data using AJAX. I also want to implement a file upload progress bar. How can I do this? Is there any way to calculate how much has already been uploaded so that I can calculate the percentage uploaded and create a progress bar?

解决方案

Note: This question is related to the jQuery form plugin. If you are searching for a pure jQuery solution, start here. There is no overall jQuery solution for all browser. So you have to use a plugin. I am using dropzone.js, which have an easy fallback for older browsers. Which plugin you prefer depends on your needs. There are a lot of good comparing post out there.

From the examples:

jQuery:

$(function() {

    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');

    $('form').ajaxForm({
        beforeSend: function() {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        complete: function(xhr) {
            status.html(xhr.responseText);
        }
    });
}); 

html:

<form action="file-echo2.php" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile"><br>
    <input type="submit" value="Upload File to Server">
</form>

<div class="progress">
    <div class="bar"></div >
    <div class="percent">0%</div >
</div>

<div id="status"></div>

you have to style the progressbar with css...

这篇关于jQuery文件上传进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆