在javascript-ajax中提交表单时如何显示进度条

Posted

技术标签:

【中文标题】在javascript-ajax中提交表单时如何显示进度条【英文标题】:How to show the progress bar when submitting the form in javascript-ajax 【发布时间】:2021-06-18 19:18:10 【问题描述】:

我已经做了进度条和一切。但是当我选择文件上传时出现问题,这意味着文件上传了两次,一次是在选择文件时,一次是提交表单,这种糟糕的用户体验,所以我只想在提交时显示进度条表单,我在后端使用 Django 和 ajax 召回

我的 html 表单

<div id="alert-box"></div>

                          <form  id="upload-form" action="." method="post" enctype="multipart/form-data">
                                % csrf_token %
                                <div id="progress-box" class="d-none">progress</div>

                                <div class="custom-file">

                                     <input type="file" class="custom-file-input" id="formGroupExampleInput2" required value="V_form.video">
                                     <label class="custom-file-label" for="formGroupExampleInput2">Choose Video...</label>
                                </div>

                                <div class="custom-file mt-5 mb-4">


                                       <input type="file" class="custom-file-input" id="file2" required value="V_form.video_poster">
                                     <label class="custom-file-label" for="formGroupExampleInput2">Choose Poster For Your Video...</label>

                                </div>

                                  <div class="d-flex justify-content-center my-3 px-3" >  <button class="btn-block btnn-color" id="heel" name="submit_v_form"> Upload</button></div>
                          </form>

javascript-Ajax

  const file_input_label = document.getElementById('file_input_label')

function input_filename()
  file_input_label.innerHTML = input.files[0].name;
  console.log(file_input_label);



 const uploadForm = document.getElementById('upload-form')
//  const input = document.getElementById('formGroupExampleInput2')
 const input = document.getElementById('formGroupExampleInput2')
 console.log(input)

 const alertBox = document.getElementById('alert-box')
 const imageBox = document.getElementById('image-box')
 const progressBox = document.getElementById('progress-box')
 const canceleBox = document.getElementById('cancel-box')
 const canceleBtn = document.getElementById('cancel-btn')



 const csrf = document.getElementsByName('csrfmiddlewaretoken')

 // whenever choose th file something happen
 input.addEventListener('change', ()=>
     progressBox.classList.remove('d-none')
     canceleBox.classList.remove('d-none')

     var filePath = input.value;

             var allowedTypes = /(\.mp4|\.mkv|\.avi|\.flv)$/i;

             if(!allowedTypes.exec(filePath))
                 alertBox.innerHTML = `<div class="alert alert-danger" role="alert">Please Upload the valid file type</div>`
                 input.value = "";
                 return false;
             

     const img_data = input.files[0]
     const url = URL.createObjectURL(img_data)
     console.log(img_data)

     const fd = new FormData()
     fd.append('csrfmiddlewaretoken', csrf[0].value)
     fd.append('video', img_data)

     $.ajax(
        type: 'POST',
        url: uploadForm.action,
        enctype: 'multipart/form-data',
        data: fd,
        beforeSend: function() 
            console.log('before')
            alertBox.innerHTML = ""
           // imageBox.innerHTML = ""
       ,
        xhr: function() 
           const xhr = new window.XMLHttpRequest();
           xhr.upload.addEventListener('progress', e=>
             // console.log(e)
             if (e.lengthComputable)
               const percent = e.loaded / e.total * 100
               console.log(percent);
               progressBox.innerHTML =
                                       `<div class="progress">
                                           <div class="progress-bar" role="progressbar" style="width: $percent%" aria-valuenow=" $percent" aria-valuemin="0" aria-valuemax="100"></div>
                                         </div>
                                         <p>$percent.toFixed(1)%</p>`
             
           )
           canceleBtn.addEventListener('click', ()=>
             xhr.abort()
             setTimeout(()=>
                 uploadForm.reset()
                 progressBox.innerHTML = ""
                 alertBox.innerHTML = ""
                 canceleBox.classList.add('d-none')
             , 1000)
           )
           return xhr
       ,
        success: function(response) 
           console.log(response)
           // imageBox.innerHTML = `<img src="$url" >`

            // imageBox.innerHTML = `<video class="card" controls src="$url">`
            alertBox.innerHTML = `<div class="alert alert-success" role="alert">Successfully uploaded your video. click upload to upload your video</div>`

        ,
        error: function(error)
          console.log(error)
           alertBox.innerHTML = `<div class="alert alert-danger" role="alert">Ups something went wrong!</div>`
        ,
        cache: false,
        contentType: false,
        processData: false,
     )
 )

【问题讨论】:

【参考方案1】:

我认为您在这里尝试实现的是仅在 Ajax 提交时显示进度条。因此,您可以在每个操作方法上添加/删除 display-none 类,如下所示。

input.addEventListener('change', () => 
    progressBox.classList.add('d-none') // Though this class is already added in html [seems redundant here].
    $.ajax(
        type: 'POST',
        beforeSend: function()  
            progressBox.classList.remove('d-none')
        ,
        success: function(response) 
            progressBox.classList.add('d-none')
        ,
        error: function(error) 
            progressBox.classList.add('d-none')
        )
 

希望这是一种解决方法,但如果这能解决您的问题,请告诉我。

【讨论】:

以上是关于在javascript-ajax中提交表单时如何显示进度条的主要内容,如果未能解决你的问题,请参考以下文章

前端文件上传-javascript-ajax

将表单结果另存为 PDF

提交表单时,会话变量会更改值。

jsp中怎样获得表单中radio的回显信息?

在提交表单后但在重定向和退出之前回显成功消息

提交表单后如何使用模态重新加载页面