Загрузка файла (изображения) с помощью ajax и jquery

#javascript #jquery #ajax #forms #file

#javascript #jquery #ajax #формы #файл

Вопрос:

Мне нужно написать функцию с использованием jquery и ajax, где при нажатии на аватар пользователь может выбрать картинку и загрузить новую. Сохранение его в папке в файлах моего сайта.

Итак, на данный момент у меня есть этот html:

             <img src="images/avatars/<?= $infos['Avatar']; ?>" onclick="setPicture()" 
            alt="avatar" class="rounded-circle clickable" width="150">

            <form class="d-none" id="formAvatar" method="post" enctype="multipart/form- 
            data">
               <input class="d-none" type="file" id="inputAvatar" name="inputAvatar" />
            </form>
  

И вот мой скрипт:

 function setPicture() {

    $('#inputAvatar').trigger('click', function() { // So here i trigger a click on the input file when the user click on his profile picture. The input is not visible by default on the page. 
    
        let userfile = $('#inputAvatar').val();
    
        if(userfile) { // here i want to check if a file has been selected but it doesn't seems to work

            $('#formAvatar').submit(); // Here i submit the form if the previous condition is true
        
            $("#formAvatar").on('submit',(function(e) { // Here if the form is submitted i send the picture to a php treatment page
            
                e.preventDefault();

                $.ajax({
        
                    type: 'POST',
                    url: 'traitements/traitement-profil.php',
                    data:  new FormData(this),
                    contentType: false,
                    cache: false,
                    processData:false,
        
                    success: function(data) {
        
                        let errorWindow = document.getElementById('erreur');

                        errorWindow.className = "alert alert-danger my-5 text-center";
                        errorWindow.innerHTML = data;
        
                    }
        
                });
            
            })
        
        )}

    });
    
}
  

Кто-нибудь может мне помочь, пожалуйста?

Ответ №1:

[1] Вы не получите значение .trigger с типом входного файла, который вам нужно использовать change

[2] Нет необходимости использовать функцию . вы можете использовать class avatar для изображения .. И разделите события, а затем запустите их на своем месте

  • Форма submit
  • Входной файл change
  • Изображение click для запуска входного файла нажмите

 $("#formAvatar").on('submit', function(e) { // Here if the form is submitted i send the picture to a php treatment page

  e.preventDefault();
  console.log('submitted');
 /* $.ajax({

      type: 'POST',
      url: 'traitements/traitement-profil.php',
      data:  new FormData(this),
      contentType: false,
      cache: false,
      processData:false,

      success: function(data) {

          let errorWindow = document.getElementById('erreur');

          errorWindow.className = "alert alert-danger my-5 text-center";
          errorWindow.innerHTML = data;

      }

  });*/

});

$('#inputAvatar').on('change', function() { // So here i trigger a click on the input file when the user click on his profile picture. The input is not visible by default on the page. 

    let userfile = $(this).val();
    if(userfile) { // here i want to check if a file has been selected but it doesn't seems to work
      $('#formAvatar').submit(); // Here i submit the form if the previous condition is true
    }
}); // close the change event
  
$('.avatar').on('click' , function(){ // trigger the input file click
  $('#inputAvatar').click();
});  
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="images/avatars/<?= $infos['Avatar']; ?>"  alt="avatar" class="avatar rounded-circle clickable" width="150">
<form class="d-none" id="formAvatar" method="post" enctype="multipart/form- 
data">
   <input class="d-none" type="file" id="inputAvatar" name="inputAvatar">
</form>  

Комментарии:

1. Работает абсолютно нормально! Большое вам спасибо!

2. С удовольствием, @The-Evil-Fox .. Хорошего дня 🙂