We have a simple form, a button for selecting multiple images and a button for loading them!

var files; // Вешаем функцию на событие // Получим данные файлов и добавим их в переменную $('input[type=file]').change(function(){ files = this.files; }); // Вешаем функцию ан событие click и отправляем AJAX запрос с данными файлов $('.submit.button').click(function( event ){ event.stopPropagation(); // Остановка происходящего event.preventDefault(); // Полная остановка происходящего // Содадим данные формы и добавим в них данные файлов из files var data = new FormData(); $.each( files, function( key, value ){ data.append( key, value ); }); // Отправляем запрос $.ajax({ url: './submit.php?uploadfiles', type: 'POST', data: data, cache: false, dataType: 'json', processData: false, // Не обрабатываем файлы (Don't process the files) contentType: false, // Так jQuery скажет серверу что это строковой запрос success: function( respond, textStatus, jqXHR ){ // Если все ОК if( typeof respond.error === 'undefined' ){ // Файлы успешно загружены, делаем что нибудь здесь console.log( respond ); // выведем пути к загруженным файлам в блок '.ajax-respond' var files_path = respond.files; var html = ''; $.each( files_path, function( key, val ){ html += val +'<br>'; } ) $('.ajax-respond').html( html ); } else{ console.log('ОШИБКИ ОТВЕТА сервера: ' + respond.error ); } }, error: function( jqXHR, textStatus, errorThrown ){ console.log('ОШИБКИ AJAX запроса: ' + textStatus ); } }); }); //PHP <?php // Переменная ответа $data = array(); echo json_encode($data); if( isset( $_GET['uploadfiles'] ) ){ $error = false; $files = array(); $uploaddir = './uploads/'; // . - текущая папка где находится submit.php // Создадим папку если её нет if( ! is_dir( $uploaddir ) ) mkdir( $uploaddir, 0777 ); // переместим файлы из временной директории в указанную foreach( $_FILES as $file ){ if( move_uploaded_file( $file['tmp_name'], $uploaddir . basename($file['name']) ) ){ $files[] = realpath( $uploaddir . $file['name'] ); } else{ $error = true; } } $data = $error ? array('error' => 'Ошибка загрузки файлов.') : array('files' => $files ); echo json_encode( $data ); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> <input type="file" multiple="multiple" accept="image/*"> <a href="#" class="submit button">Загрузить файлы</a> <div class="ajax-respond"></div> </div> 

I just can’t add a check on the file type (I just need pictures) and make changes to the file name.

  • in the $ _FILES array, each file has a key "type" - try using it to check the type - Taarim

1 answer 1

The type of file is important to us from the point of view of the web server, since it is the web server that will decide how to use this file. And the web server will decide this by extension.

Therefore, you just need to get the file name extension and check its presence in the array of allowed values

 $allowedExts = array('png', 'jpeg', 'jpg', 'gif'); $ext = pathinfo($file['name'], PATHINFO_EXTENSION); if( !in_array($ext, $allowedExts) ) { $error = ['error' => 'invalid image format']; } 

The file name must be changed to random. For this purpose, I prefer md5 from the contents of the file - this way you can avoid duplicates at the same time.

 $name = md5_file($file['tmp_name']).".$ext"; 
  • Thanks did, everything works - JuniorCoder