从ajax响应更新此Div

时间:2017-09-26 07:15:04

标签: javascript jquery html css ajax

我有以下form基本上接受文件上传,然后显示上传status。最终status转到status id。但是,我有多个表单,例如,当您更新第二个表单时,status显示在第一个form而不是第二个。{/ p>

我如何分别更新它们,具体取决于更新的那些。

这是我的代码:

<script>
function _(el) {
  return document.getElementById(el);
}

function uploadFile(element) {
  var file = _("file1").files[0];
  alert(file.name+" | "+file.size+" | "+file.type);
  var formdata = new FormData();
  formdata.append("file1", file);
  var ajax = new XMLHttpRequest();
  var uploadValue = element.getAttribute("data-uploadValue");
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.addEventListener("error", errorHandler, false);
  ajax.addEventListener("abort", abortHandler, false);
  ajax.open("POST", "/upload/" + uploadValue); //
  ajax.send(formdata);
}

function progressHandler(event) {
  _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
  var percent = (event.loaded / event.total) * 100;
  _("progressBar").value = Math.round(percent);
  _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}

function completeHandler(event) {
  _("status").innerHTML = event.target.responseText;
  _("progressBar").value = 0; //wil clear progress bar after successful upload
}

function errorHandler(event) {
  _("status").innerHTML = "Upload Failed";
}

function abortHandler(event) {
  _("status").innerHTML = "Upload Aborted";
}
</script>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>

更新1 : 将JS改为更依赖的东西。

更新2 : 决定将JS放在与表单相同的输出循环中(因此有多个脚本,每个表单一个)并在每个id中插入一个唯一的数字 - 基本上使id唯一。虽然做法不好,但这仍然无法解决我的问题。

更新3 我在每个上传表单之前有另一个表单,其中包含一个文本区域 - 这似乎导致了问题。 Alex Kudryashev的回答是在没有这些额外表格的情况下进行的,但没有。

4 个答案:

答案 0 :(得分:1)

OP中的问题在getElementById中,它仅返回第一个元素。工作解决方案是在绑定到表单的闭包中找到每个表单内的元素(多个)。这样的事情:
更新

  

我在每个上传表单之前都有另一个表单,其中包含一个文本区域    - 这似乎引起了问题。亚历克斯Kudryashev回答工作没有这些额外的形式,但没有。

查看代码中的更新。

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            for (var i = 0, form; form = document.forms[i]; ++i) {//iterate throu forms
                initForm(form);
            }
        });
        function initForm(frm) {
            //find elements of interest inside the form
            var fileUpload = frm.file1;//get by 'name' attribute inside the form
            var statusInfo = frm.querySelector('.status');
            var progressBar = frm.querySelector('.progress');
            var progressInfo = frm.querySelector('.loaded_n_total');

            //update. 'textarea' is in a separate form which doesn't contain 'file1'
            if (fileUpload)
               fileUpload.addEventListener('change', uploadFile);

            function uploadFile(e) {//'e' is 'change' event. It isn't used and may be ommited
                var file = this.files[0];// 'this' is fileUpload element
                //alert(file.name + " | " + file.size + " | " + file.type);
                console.log(file);
                var formdata = new FormData();
                formdata.append("file1", file, file.name);

                //update. A form with fileUpload contains other elements
                for (var i = 0, el; el = this.form.elements[i]; ++i) {
                    if (el !== this)
                        formdata.append(el.name, el.value);
                }

                statusInfo.innerHTML = 'prepare upload';
                var ajax = new XMLHttpRequest();
                var uploadValue = this.getAttribute("data-uploadValue");
                ajax.upload.addEventListener("progress", progressHandler, false);
                ajax.addEventListener("load", completeHandler, false);
                ajax.addEventListener("error", errorHandler, false);
                ajax.addEventListener("abort", abortHandler, false);
                ajax.open("POST", "/upload/" + uploadValue); //
                ajax.send(formdata);
            }
            function progressHandler(event) {
                progressInfo.innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
                var percent = (event.loaded / event.total) * 100;
                progressBar.value = Math.round(percent);
                statusInfo.innerHTML = Math.round(percent) + "% uploaded... please wait";
            }

            function completeHandler(event) {
                statusInfo.innerHTML = event.target.responseText;
                progressBar.value = 0; //wil clear progress bar after successful upload
            }

            function errorHandler(event) {
                statusInfo.innerHTML = "Upload Failed";
            }

            function abortHandler(event) {
                statusInfo.innerHTML = "Upload Aborted";
            }
        }//initForm

    </script>
</head>
<body>
    <form enctype="multipart/form-data" method="post">
        <div class="file has-name is-fullwidth is-info">
            <label class="file-label">
                <input class="file-input" type="file" name="file1" data-uploadValue="form/1"><br>
                <span class="file-cta">
                    <span class="file-icon">
                        <i class="fa fa-upload"></i>
                    </span>
                    <span class="file-label">
                        Choose a file…
                    </span>
                </span>
                <div class="file-name">
                    <div style="color:red;" class="status"></div>
                    Supported file types: .png, .jpg, .jpeg and .gif
                </div>
            </label>
            <div style="display:none">
                <p class="loaded_n_total"></p>
                <progress class="progress" value="0" max="100" style="width:300px;"></progress>
            </div>
        </div>
    </form>
    <form enctype="multipart/form-data" method="post">
        <div class="file has-name is-fullwidth is-info">
            <label class="file-label">
                <input class="file-input" type="file" name="file1" data-uploadValue="form/2"
                       ><br>
                <span class="file-cta">
                    <span class="file-icon">
                        <i class="fa fa-upload"></i>
                    </span>
                    <span class="file-label">
                        Choose a file…
                    </span>
                </span>
                <div class="file-name">
                    <div style="color:red;" class="status"></div>
                    Supported file types: .png, .jpg, .jpeg and .gif
                </div>
            </label>
            <div style="display:none">
                <p class="loaded_n_total"></p>
                <progress class="progress" value="0" max="100" style="width:300px;"></progress>
            </div>
        </div>
    </form>
</body>
</html>

答案 1 :(得分:0)

您不应在页面上多次定义相同的id。因为当你这样做,并使用id定义jquery代码时,DOM会考虑从文档的顶部开始的第一个id。因此,总是首先出现特定的id将会被引用。

所以你需要将status更改为类,所以:class="status"然后在ajax函数中引用此类并引用您已经汇总的表单,因此它只会将您的状态附加到相关仅元素。检查以下代码:

$('#uploadform').ajaxForm({
    beforeSend: function() {
        $(this).find('.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);
        //console.log(percentVal, position, total);
    },
    success: function() {
        var percentVal = '100%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    complete: function(xhr) {
        $(this).find('.status').html(xhr.responseText);
    }
});

答案 2 :(得分:0)

让我们来看看这部分:

    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
        //console.log(percentVal, position, total);
    },

因为您的代码引用了条和百分比如下:

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

我期望发生的事情不仅是状态只会更新第一个,而且形式1,2中的条形和百分比直到n在更新时始终显示相同的值,任何发生的更改都会反映到所有其他人也是如此。这是由于每个变量绑定的DOM。因此,我将对您的代码进行一些更改,并以正确的方式执行此操作:

<script>
    (function() {

        var forms = $(".some-upload-forms");

        for (var i = 0; i < forms.length; i++){
            initializeFormEvents(forms[i]);
        }

        function initializeFormEvents(form){
            var bar = form.find('.bar');
            var percent = form.find('.percent');
            var status = form.find('#status');
            var uploadForm = form.find("#uploadform");

            uploadForm.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);
                    //console.log(percentVal, position, total);
                },
                success: function() {
                    var percentVal = '100%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                complete: function(xhr) {
                    status.html(xhr.responseText);
                }
            })
        }
    })();


    </script>

你的HTML:

<div class='some-upload-forms">
    <form id="uploadform" enctype="multipart/form-data" method="post">
        <div class="file has-name is-fullwidth is-info">
          <label class="file-label">
            <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
            <span class="file-cta">
              <span class="file-icon">
                <i class="fa fa-upload"></i>
              </span>
              <span class="file-label">
                Choose a file…
              </span>
            </span>
            <span class="file-name">
              <div style="color:red;" id="status"></div>
              Supported file types: .png, .jpg, .jpeg and .gif
            </span>
          </label>
          <div style="display:none"><p id="loaded_n_total"></p>
          <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
        </div>
    </form>
</div>

然后您可以在一个页面中复制越来越多的表单,请确保从 开始重复;

答案 3 :(得分:0)

为了使您的上传器成为有效的可重复形式,您需要做的就是浏览每个表单并将id替换为有意义的唯一表单,并允许每个实例单独运行。

我将代码分为两步。第一步是将无效的HTML转换为有效的HTML:

function runner(index) {
  var form = document.getElementById('upload_form');
  if (!form) return false;
  form.id = 'upload_form-' + index;
  var children = document.querySelectorAll('#upload_form-' + index + ' *');
  for (i = 0; i < children.length; i++) {
    if (children[i].id) {
      children[i].id = children[i].id + '-' + index;
    }
  }
  return true;
}

var index = 0;

while (runner(index)) {
  index++;
}

这会遍历您网页中ID为upload_form的所有表单,并在他们的index和他们孩子的id之后添加一个漂亮的小id ,确保它们变得独一无二。

这是一个小测试:

function runner(index) {
  var form = document.getElementById('upload_form');
  if (!form) return false;
  form.id = 'upload_form-' + index;
  var children = document.querySelectorAll('#upload_form-' + index + ' *');
  for (i = 0; i < children.length; i++) {
    if (children[i].id) {
      children[i].id = children[i].id + '-' + index;
    }
  }
  return true;
}

var index = 0;

while (runner(index)) {
  index++;
}
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <div class="file has-name is-fullwidth is-info">
    <label class="file-label">
        <input class="file-input" type="file" name="file1" id="file1" data-uploadValue="{{ item[0] }}"  onchange="uploadFile(this)"><br>
        <span class="file-cta">
          <span class="file-icon">
            <i class="fa fa-upload"></i>
          </span>
          <span class="file-label">
            Choose a file…
          </span>
        </span>
        <span class="file-name">
          <div style="color:red;" id="status"></div>
          Supported file types: .png, .jpg, .jpeg and .gif
        </span>
      </label>
    <div style="display:none">
      <p id="loaded_n_total"></p>
      <progress id="progressBar" class="progress" value="0" max="100" style="width:300px;"></progress></div>
  </div>
</form>

运行它并检查表单,你会发现它们得到了索引,因此他们的孩子也有id个属性。

第二步是确保您当前的代码查找,获取并使用父窗体的id,以便正确选择其中元素的id。为此,我首先获取正在使用的输入的父表单索引,然后使用闭包将此index传递给每个后续函数调用,因此_()始终选择正确的元素。 / p>

function _(el, index) {
  return document.getElementById(el + '-' + index);
}

function uploadFile(element) {
  var formId = element.closest('form').id,
    index = formId.split('-')[formId.split('-').length - 1],
    file = _("file1", index).files[0];
  alert(file.name + " | " + file.size + " | " + file.type);
  var formdata = new FormData();
  formdata.append("file1", file);
  var ajax = new XMLHttpRequest();
  var uploadValue = element.getAttribute("data-uploadValue");
  ajax.upload.addEventListener("progress", 
    (function(n) { progressHandler(event, n) })(index), 
    false);
  ajax.addEventListener("load", 
    (function(n) { completeHandler(event, n) })(index), 
    false);
  ajax.addEventListener("error", 
    (function(n) { errorHandler(event, n) })(index), 
    false);
  ajax.addEventListener("abort", 
    (function(n) { abortHandler(event, n) })(index), 
    false);
  ajax.open("POST", "/upload/" + uploadValue); //
  ajax.send(formdata);
}

function progressHandler(event, index) {
  _("loaded_n_total", index).innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
  var percent = event.total ? event.loaded * 100 / event.total : 0;
  _("progressBar", index).value = Math.round(percent);
  _("status", index).innerHTML = Math.round(percent) + "% uploaded... please wait";
}

function completeHandler(event, index) {
  _("status", index).innerHTML = event.target.responseText;
  _("progressBar", index).value = 0; //wil clear progress bar after successful upload
}

function errorHandler(event, index) {
  _("status", index).innerHTML = "Upload Failed";
}

function abortHandler(event, index) {
  _("status", index).innerHTML = "Upload Aborted";
}

旁注:我冒昧地改变了

var percent = (event.loaded / event.total) * 100;

...进入:

var percent = event.total ? event.loaded * 100 / event.total : 0;

...,因为(可能由于不允许在SO上发布POST),event.total 0正在制作percent NaN,在下一个生成错误线。如果您的实例中没有此问题,请确保将此行更改回适合您的任何内容。

就我可以测试而言,它似乎有效,唯一的错误是关于SO不允许POST请求,一旦文件被选中并附加到表单。

如果您遇到任何麻烦,请告诉我,我会试着弄清楚发生了什么。