将其他输入与FormData关联到每个上传的文件

时间:2018-11-03 11:12:31

标签: javascript filereader form-data

我有一个图像多上传输入,它显示图像预览,并允许在提交之前使用FormData,FileReader和AJAX对其进行编辑。

但是我不知道如何将图像标题的其他输入字段关联到每个上传的文件。我试图用相同的代码创建这些输入,这些代码显示预览图像,然后使用AJAX和原始数据上传它们。

问题是我不知道如何将这些输入的值与每个上载的文件相关联,因为相应的数组是混合在一起的。我的意思是将信息发送到服务器,以便可以某种方式识别哪个输入值对应于哪个文件。
这是JS代码:

$("#files").on("change", File_Selection);
$("#create-rankit-imgs").on("submit", Submit_form);
files_selection = $("#files-selection");
var uploaded_files = [];


function File_Selection(e) {

  var files = e.target.files;
  var files_array = Array.prototype.slice.call(files);

  for (let f of files_array ){

    uploaded_files.push(f);
    var reader = new FileReader();

    reader.onprogress = function (e) {
      $(".loader").css("display", "block")
    }

    reader.onloadend = function (e) {
      $(".loader").hide() 
    }

    reader.onload = function (e) {
      /*I TRIED HERE TO INSERT THE TITLE INPUT TOGETHER WITH THE PREVIEW IMAGE*/
      var files_selection_preview = "<div><img id=\"" + "preview-upload-image" + i + "\" src=\"" + e.target.result + "\"> <input id=\"rankit_title\" class=\"form-control img-title\" type=\"text\" name=\"img-title-" + i + "\" > </div>" ;
      files_selection.append(files_selection_preview);
    }    
    reader.readAsDataURL(f);
  } 
}

function Submit_form(e) {
  /*Submit the content in "files_array" to the server via AJAX and formdata"*/
  e.preventDefault();
  var formdata = new FormData();

  for(var i=0, len=files_array.length; i<len; i++) {
    formdata.append('files', storedFiles[i]);
  }

  var img_titles = Array.prototype.map.call(
    document.querySelectorAll('.img-title'),
    element => element.value);

  /*I SEND THE CONTENT OF IMAGE TITLES SUCCESSFULLY, BUT NOT MATCHING WITH FORMDATA, BECAUSE THEY HAVE DIFFERENT ORDER*/
  formdata.append('img_titles', JSON.stringify(img_titles));
  $.ajax({
    url: '{% url 'images:create' %}',
    type: "POST",
    data: formdata,
    // necessary options for file upload:
    processData: false,
    contentType: false,
    cache: false,
    //redirect in case of success
    success: function(data){
      if (data['status']=='ok'){
        window.location.replace("/rankit/" + data['rankit']);
      }}
  });
}

0 个答案:

没有答案