简体   繁体   English

使用进度条上传文件

[英]Upload file with progress bar

I create this code to upload file usin ajax and php and I want to add progress bar to show percent of upload. 我创建此代码以使用ajax和php上传文件,我想添加进度条以显示上传百分比。

this my code 这是我的代码

<script>
   $("form#data").submit(function(){
    var formData = new FormData($(this)[0]);
    $.ajax({
        url: "functions/video.php",
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            document.getElementById("status").innerHTML = data;
        },
        cache: false,
        contentType: false,
        processData: false
    });
    return false;
});
</script>
<form id="data" method="post" enctype="multipart/form-data">
<input name="up_vid" type="file" id="up_vid"/>
<div class="upload_v_icon"></div>
<div class="video_info">
    <input type="text" name="video_title" placeholder="Video title" />
    <input type="text" name="tags" placeholder="funny,9gag,nice,crazy ..."/>
    <textarea name="description" placeholder="Description"></textarea>
    </div>
    <div class="bg_upload">
    <p>When you upload this video your are agree with <a href="">Terms</a> of service.</p>
    <button>Begin Upload</button>
    </div>
</form>

Thank you. 谢谢。

This assumes a 1px wide gif called "progress.gif" is present. 假设存在一个称为“ progress.gif”的1px宽的gif。 Set the color of this to the color you want your progress bar to appear. 将此颜色设置为您希望进度条显示的颜色。

Add something like this to your css: 在您的CSS中添加以下内容:

.uploadBar {
   background-image:url(/images/progress.gif);
   background-position: -1px;
   background-repeat:no-repeat;
   background-size=0% 100%; width:100%;
   position: relative; overflow: hidden;
}

Add something like this to your $.ajax(); 在您的$ .ajax()中添加类似的内容。

xhr: function() {
   var xhr = new window.XMLHttpRequest();
   //Upload progress
   xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
      var percentComplete = evt.loaded / evt.total;
      console.log(percentComplete);
      $('.uploadBar').css({ backgroundSize: (percentComplete*100) + '%'});
      }
   }, false);
   return xhr;
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM