How to add a File object to a FileList collection in JavaScript?

I am working on a drag file upload field.

I can return a FileList object containing the file specified by the user. I have a hidden file input field, which then I want to add a file object to then send form data via AJAX.

The problem that I am facing is that I cannot copy the file object to the file input field. Here is how I am trying to do this:

var files = evt.dataTransfer.files; // FileList object.
var fileUploadElem = document.getElementById(fileUploadId);

// trying to copy the first file of files into the file upload field
fileUploadElem.files[0] = files[0];

// this statement returns '0' instead of '1'
console.log('fileUploadElem length: '+fileUploadElem.files.length);

Appreciate any tips or pointers.

+4
source share
2 answers

, , , JavaScript Chrome, , Firefox, .

0

MDN , FormData:

function sendForm() {
  var output = document.getElementById("output");
  var data = new FormData(document.getElementById("fileinfo"));

  data.append("CustomField", "This is some extra data");

  var xhr = new XMLHttpRequest();
  xhr.open("POST", "stash.pl", false)
  xhr.send(data);
  if (xhr.status == 200) {
    output.innerHTML += "Uploaded!<br />";
  } else {
    output.innerHTML += "Error " + xhr.status + " occurred uploading your file.<br />";
  }
}
0

Source: https://habr.com/ru/post/1544190/


All Articles