Измените тип ввода = «файл», чтобы получить значение из массива

#javascript #html #jquery #forms

#javascript #HTML #jquery #формы

Вопрос:

Перед вводом изображений в базу данных я использовал js для отображения пользовательских изображений до их добавления в базу данных, что мне удалось сделать. Но я также хочу добавить функцию, которая может удалять определенные изображения.

У меня есть тип ввода = «файл», откуда я вставляю данные с компьютера.

 <div class="form-group">
<input class="form__upload" 
  name="images" 
  id="creative---Point19981022--newPostPhoto" 
  type="file" multiple="" accept="image/*">
<label for="creative---Point19981022--newPostPhoto">Choose photo</label>
</div>
 

Чтобы добавить функциональность стеклоочистителя, мы сохранили входные данные в массиве объектов, я создал новый массив, в котором я храню данные, которые хочу удалить, а затем использую array.filter для разделения информации.

 $this.data('delimg'); -> <div class="delete_image_output" data-delimg="0">x</div>
 

 let prepareArrayList = new Array();

  $(document).on('click','.delete_image_output',function(){
  //Get Image From Fill
  let filesArr = document.getElementById('creative---Point19981022--newPostPhoto').files;
  let arrayImg = [...filesArr];
  //Delegation which get data-delimg value
  let $this = $(this);
  let renderOutpudId = $this.data('delimg');
  //get value started from data-delimg value
  const delElelemnt = arrayImg[renderOutpudId];
  //push deleted value in a new array which will by use to make a filter
   prepareArrayList.push(delElelemnt)

   //Make a filter with value coming from array with deleted element
   arrayImg = arrayImg.filter(f => !prepareArrayList.includes(f));

    //at the end arrayImg will has the remaining values
    console.log(arrayImg)

});
 

В конце концов мне удается получить массив с выбранными изображениями, но возникает проблема с сохранением информации в базе данных.

Но как я могу изменить код в структуре ниже, вместо значения из ввода, чтобы получить значение из массива выше?

 let createPost = document.querySelector('.createNew--post--creativePoint');
if(createPost){
createPost.addEventListener('submit',(crPos)=>{
    crPos.preventDefault();

    let filesImg = document.getElementById('creative---Point19981022--newPostPhoto').files;
    const postData = new FormData();
        postData.append('title',document.getElementById('creative---Point19981022-create--newPostTitle').value);
        postData.append('link',document.getElementById('creative---Point19981022-create--newPostLink').value);
        postData.append('description',document.getElementById('creative---Point19981022--newPostDescription').value);
        postData.append('datePost',document.getElementById('creative---Point19981022--dataNow').value);
        // Using For loop for miltiple images
        for (let p = 0; p < filesImg.length; p  ) {
            postData.append('images', filesImg[p]);
        }
        postData.append('youtubeEmbedVideo',document.getElementById('creative---Point199810022-create-embedIdOnly').value);
        postData.append('author',document.getElementById('creative---Point19981022--authorDate').value);
    
    // Do not allow posts if all fields al empty
    if( document.getElementById('creative---Point19981022-create--newPostTitle').value != "" || 
        document.getElementById('creative---Point19981022--newPostPhoto').files.length != 0  || 
        document.getElementById('creative---Point19981022-create--newPostLink').value  != "" ||
        document.getElementById('creative---Point19981022--newPostDescription').value  != "" ||
        document.getElementById('creative---Point199810022-create-embedIdOnly').value  != ""){
            //createPostFnc(postData);
            console.log(filesImg)
    }else{
        showAlert('error',' No field was filled in, the post cannot be processed');
    }    
});
 

filesImg вместо входного значения принимает значение из массива и корректирует структуру

Ответ №1:

Итак, если я правильно понимаю, вы хотите отправить отфильтрованный массив файлов вместо всех файлов, которые были выбраны input .

Я бы попробовал использовать троичный оператор filesImg , чтобы проверить, является ли «отфильтрованный массив» пустым или нет. Потому что, возможно, пользователь не удалил ни одного…

 let filesImg = (arrayImg.length>0) ? arrayImg : document.getElementById('creative---Point19981022--newPostPhoto').files;
 

Вы должны объявить arrayImg в глобальной области видимости, как вы это делали для prepareArrayList .