user1128677 user1128677 - 2 years ago 820
Javascript Question

JavaScript delete File from FileList to be uploaded

There is the code Everything looks fine but I want to delete some of the files from the set.

I have already found these:

I know that
object is readonly, so I can just copy the files to a new array. But what should I do with this new array of
objects? I can't assign it to the

Answer Source

Since you cannot edit the Read Only input.files attribute, you must upload a form using XMLHttpRequest and send a FormData object. I will also show you how to use URL.createObjectURL to more easily get a URI from the File object:

var SomeCl = {
  count: 0,
  init: function() {
  onInputChange: function() {
    // reset preview
    // reset count
    SomeCl.count = 0;
    // process files
    SomeCl.processFiles(this.files, function(files) {
      // filtered files

      // uncomment this line to upload the filtered files
      SomeCl.upload('url', 'POST', $('#upload').get(0), files, 'images[]');
  processFiles: function(files, callback) {
    // your filter logic goes here, this is just example

    // filtered files
    var upload = [];

    // limit to first 4 image files, function(file) {
      if (file.type.slice(0, 5) === 'image' && upload.length < 4) {
        // add file to filter
        // increment count
        // show preview

  upload: function(method, url, form, files, filename) {
    // create a FormData object from the form
    var fd = new FormData(form);
    // delete the files in the <form> from the FormData
    // add the filtered files instead
    fd.append(filename, files);

    // demonstrate that the entire form has been attached
    for (var key of fd.keys()) {
      console.log(key, fd.getAll(key));

    // use xhr request
    var xhr = new XMLHttpRequest();, url, true);
    xhr.addEventListener('progress', function(e) {
      console.log('lengthComputable', e.lengthComputable);
      console.log(e.loaded + '/' +;
    xhr.addEventListener('load', function(e) {
    xhr.addEventListener('error', function(e) {
      console.log('this is just a demo');
  preview: function(file) {
    // create a temporary URI from the File
    var url = URL.createObjectURL(file);
    // append a preview
    $('.container').append($('<img/>').attr('src', url));

.container img {
  max-width: 250px;
  max-height: 250px;
<script src=""></script>
<form id="upload">
  <input name="other" type="hidden" value="something else">
  <input name="images[]" id="images" multiple="multiple" type="file">
  <div class="container"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download