Как заменить файлы в input file

Возник вопрос как в file input поменять файлы. В коде, после выбора картинок, она сразу отрисовываются на странице. Получается, что если добавить картинки, после этого парочку удалить, то объекты input.files и images_array одинаковые. После всех манипуляций с картинками мне нужно массив images_array положить в file input. Как этого добиться?

let images_array = new DataTransfer();

$("input[type=file]").change(function() {

  let files = this.files;
  let images = $("#images-list .row");

  $.each(files, function(key, file) {
    let reader = new FileReader();

    images_array.items.add(file);

    reader.onload = function(e) {
      images.append(`
                    <div class="col-md-4 col-sm-2 image">
                        <div class="card">
                            
                            <img class="card-img-top" style="height: 100px; object-fit: cover" src="${e.target.result}" alt="Card image cap">
                            
                            <div class="card-body d-flex justify-content-between">
                                                            
                                <div class="flex-grow-1 form-check form-check-inline border rounded btn">
                                    <input class="form-check-input" type="radio" id="background-${file.name}" value=${file.name}>
                                    <label class="form-check-label" for="background-${file.name}" value="on">Фон</label>
                                </div>
                                <input hidden class="form-check-input" type="text" name="background" id="background-${file.name}" value=${file.name}>

                                <button class="btn btn-danger images-remove_button">X</button>
                        
                            </div>
                            
                        </div>
                    </div>
                `);
    };
    reader.readAsDataURL(file);
  });

  this.files = images_array.files; // подменить значение в Input
});

$(document).on("click", ".images-remove_button", function(e) {
  e.preventDefault();

  let index = $(".images-remove_button").index($(this));
  let input = $("input[type=file]");
  $(this).closest(".image").remove();

  images_array.items.remove(index); 

  input.files = images_array.files; //подменить значение в Input
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

<div class="form-group">

  <label class="h6" for="exampleFormControlFile1">Загрузить изображения</label>
  <input type="file" name="files[]" class="form-control-file" id="exampleFormControlFile1" multiple>

  <div id="images-list" class="mt-3">
    <input id="images-path" hidden type="text" value="projects">
    <div class="row"></div>
  </div>
</div>


Ответы (1 шт):

Автор решения: MaXX

Необходимо строку подмены значений в input переместить во внутрь конструкции reader.onload.

let images_array = new DataTransfer();

$("input[type=file]").change(function() {

  let files = this.files;
  let images = $("#images-list .row");

  $.each(files, function(key, file) {
    let reader = new FileReader();

    images_array.items.add(file);

    reader.onload = function(e) {
      images.append(`
        <div class="col-md-4 col-sm-2 image">
            <div class="card">
                
                <img class="card-img-top" style="height: 100px; object-fit: cover" 
                     src="${e.target.result}" alt="Card image cap">
                
                <div class="card-body d-flex justify-content-between">
                                                
                    <div class="flex-grow-1 form-check form-check-inline border rounded btn">
                        <input class="form-check-input" type="radio" id="background-${file.name}" value=${file.name}>
                        <label class="form-check-label" for="background-${file.name}" value="on">Фон</label>
                    </div>
                    <input hidden class="form-check-input" type="text" 
                           name="background" id="background-${file.name}" value=${file.name}>

                    <button class="btn btn-danger images-remove_button">X</button>
            
                </div>
                
            </div>
        </div>
    `);

          input.files = images_array.files; // !!!!! подменить значение в Input

    };
    reader.readAsDataURL(file);
  });

  this.files = images_array.files; // подменить значение в Input
});

$(document).on("click", ".images-remove_button", function(e) {
  e.preventDefault();

  let index = $(".images-remove_button").index($(this));
  let input = $("input[type=file]");
  $(this).closest(".image").remove();

  images_array.items.remove(index); 

});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" 
  integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
  crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
  integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
  crossorigin="anonymous"></script>

<div class="form-group">

  <label class="h6" for="exampleFormControlFile1">Загрузить изображения</label>
  <input type="file" name="files[]" class="form-control-file" id="exampleFormControlFile1" multiple>

  <div id="images-list" class="mt-3">
    <input id="images-path" hidden type="text" value="projects">
    <div class="row"></div>
  </div>
</div>

→ Ссылка