Hello. I make a form of uploading photos to the site by the user with validation and display of thumbnails. On devices, I get an ext_error error when I try to upload photos already in the library, and if I take a picture, it is validated. Can you tell me what's wrong with the code?
//Uploader (function() { uploaded = 0; var fileSelect = document.getElementById('file-select'), max_limit = 1; var upload = function(files) { if ((files.length <= max_limit) && ( uploaded < max_limit )) { var formData = new FormData(), xhr = new XMLHttpRequest(), x; for (x = 0; x < files.length; x++) { formData.append('file[]', files[x]); } formData.append('action', 'upload'); xhr.open('post', ''); xhr.send(formData); xhr.onload = function() { var data = JSON.parse(this.responseText); //Проверяем статус ошибки if (data['status'] === undefined) { uploaded = uploaded + data.length; displayUploads(data); } else { if (data['status'] === "max_files_error") { //Выводим ошибку "Вы не можете загрузить больше " + max_limit + " файлов" } else if (data['status'] === "ext_error") { //Выводим ошибку "Разрешено загружать только jpg, gif, png." } } } } else { //Выводим ошибку "Sorry, you can download only one photo :(" } } fileSelect.onchange = function(e) { e.preventDefault(); upload(fileSelect.files); }; }()); And here is the server code:
private function upload_project_files($max_files = 1, $allowed_ext = array('png', 'jpg', 'gif' , 'tiff')) { header('Content-Type: application/json'); //Ограничения на загрузку // $allowed_ext = array('png', 'jpg', 'gif'); // $max_files = 3; if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' ); $uploadedfiles = array(); $upload_overrides = array( 'test_form' => false ); $files = $_FILES['file']; if ( count($files['name']) > $max_files && count($files['name']) != 0) { echo '{"status":"max_files_error"}'; exit; } foreach ($files['name'] as $key => $value) { $ext = pathinfo($files['name'][$key], PATHINFO_EXTENSION); if(!in_array(strtolower($ext), $allowed_ext)){ echo '{"status":"ext_error"}'; exit; } } foreach ($files['name'] as $key => $value) { if ($files['name'][$key]) { $file = array( 'name' => $files['name'][$key], 'type' => $files['type'][$key], 'tmp_name' => $files['tmp_name'][$key], 'error' => $files['error'][$key], 'size' => $files['size'][$key] ); $file = wp_handle_upload($file, $upload_overrides); $uploadedfiles[] = array('url' => $file['url'],'path' => $file['file']); } } die(json_encode($uploadedfiles)); }
$allowed_ext, you apparently forgot it. - Ivan Pshenitsynvar_dump($_FILES);do to check what comes in there. It bothers me a little that you refer to$_FILES['file']['name']as an array and iterate over it, although it doesn't look like there should be an array. - Ivan Pshenitsyn