使用jQuery的文件上传进度条我正在尝试在我的项目中实现Ajax文件上传功能。为此,我使用jQuery;我的代码使用Ajax提交数据。我还想实现一个文件上传进度条。我该怎么做?有没有方法来计算已经上传了多少,这样我就可以计算上传的百分比并创建一个进度条了吗?
3 回答
一只斗牛犬
TA贡献1784条经验 获得超2个赞
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>
白猪掌柜的
TA贡献1893条经验 获得超10个赞
$.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; percentComplete = parseInt(percentComplete * 100); console.log(percentComplete); if (percentComplete === 100) { } } }, false); return xhr; }, url: posturlfile, type: "POST", data: JSON.stringify(fileuploaddata), contentType: "application/json", dataType: "json", success: function(result) { console.log(result); }});
桃花长相依
TA贡献1860条经验 获得超8个赞
ajax = new XMLHttpRequest();ajax.onreadystatechange = function () { if (ajax.status) { if (ajax.status == 200 && (ajax.readyState == 4)){ //To do tasks if any, when upload is completed } }}ajax.upload.addEventListener("progress", function (event) { var percent = (event.loaded / event.total) * 100; //**percent** variable can be used for modifying the length of your progress bar. console.log(percent);});ajax.open("POST", 'your file upload link', true);ajax.send(formData);//ajax.send is for uploading form data.
- 3 回答
- 0 关注
- 683 浏览
相关问题推荐
添加回答
举报
0/150
提交
取消