Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a file into a File Input field

I am trying to create a file drag and drop feature.

I've the drag and drop working from the div and handling the file.

Now I now would like to append this file to the Input[type=file] of the form .

How could I do that?

I tried uploadFormData.append("files[]",f); and derivates but it doesnt work. My debugging was submit the form and check the headers to see if the file was sent.

Could anyone point me in the right direction on how achieve this?

    <form enctype="multipart/form-data" id="yourregularuploadformId">
         <input type="file" name="files[]" multiple="multiple">
    </form>

<script>
      var uploadFormData = new FormData(jQuery("#yourregularuploadformId")[0]);

        function handleFileSelect(evt) {
        evt.stopPropagation();
        evt.preventDefault();

        var files = evt.dataTransfer.files; // FileList object.

        // files is a FileList of File objects. List some properties.

        var output = [];


        for (var i = 0, f; f = files[i]; i++) {
          output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                      f.size, ' bytes, last modified: ',
                      f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                      '</li>');
               uploadFormData.append("files[]",f);
        }

        document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
      }
</script>
like image 251
Jonathan Thurft Avatar asked Dec 04 '25 07:12

Jonathan Thurft


1 Answers

Create a DataTransfer object, add files via its items field, obtain the FileList of files, then assign it to inputEl.files:

document.getElementById("add-file").addEventListener("click", ev => {
  ev.preventDefault();
  const inputEl = document.getElementById("formfiles");
  
  const dt = new DataTransfer();
  
  // Add items here, possibly from the inputEl's existing list
  dt.items.add(new File(
    ["hello, world!"], "hello_world.txt"
  ));
  
  // Set the input's files
  inputEl.files = dt.files;
});
<input type="file" id="formfiles" name="formfiles" multiple />
<br>
<button id="add-file">Add File Dynamically</button>
like image 161
Colonel Thirty Two Avatar answered Dec 07 '25 03:12

Colonel Thirty Two



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!