Jquery input file php

Содержание
  1. Работа с Input File JS/jQuery
  2. Очистка поля
  3. Пример:
  4. Проверка заполнения
  5. Пример:
  6. Получить количество выбранных файлов
  7. Пример:
  8. Получить имя выбранного файла
  9. Пример:
  10. Имена всех выбранных файлов (multiple)
  11. Пример:
  12. Получить тип выбранного файла (MIME)
  13. Пример:
  14. Типы всех выбранных файлов (multiple)
  15. Пример:
  16. Получить размер выбранного файла
  17. Пример:
  18. Размер всех выбранных файлов (multiple)
  19. Пример:
  20. Комментарии
  21. Другие публикации
  22. Загрузка файлов через jQuery AJAX
  23. Отправка одного файла
  24. Код скрипта upload.php
  25. How to Create a Custom File Input with jQuery, CSS3 and PHP
  26. How to Create a Custom File Input with jQuery, CSS3 and PHP
  27. Setting up the Project
  28. How it Works
  29. Building the Plugin
  30. Attaching the Events
  31. Improving Usability
  32. Fallback for Old Browsers
  33. Customizing the Appearance
  34. Retrieving the Files on the Server
  35. Conclusion
  36. Jquery input file php
  37. Анимация набора текста на jQuery
  38. Временная шкала на jQuery
  39. Заметка: Перезагрузка и редирект на JavaScript
  40. Рисуем диаграмму Ганта
  41. AJAX и PHP: загрузка файла
  42. Stimed — стили в зависимости от времени суток

Работа с Input File JS/jQuery

Сборник приёмов jQuery для работы с полями загрузки файлов через интерфейс File.

Во всех примерах используется следующий HTML код:

И поле для выбора нескольких файлов:

Очистка поля

$("#file").val(null); /* или */ document.getElementById("file").value = null;

Пример:

Проверка заполнения

if ($("#file").val() == '') < alert("Файл не выбран"); >else < alert("Файл выбран"); >/* или */ if (document.getElementById("file").value == '') < alert("Файл не выбран"); >else

Пример:

Получить количество выбранных файлов

$('#btn').click(function()< alert($("#file")[0].files.length); >); /* или */ $('#btn').click(function()< alert(document.getElementById("file").files.length); >); 

Пример:

Получить имя выбранного файла

Свойство File.name возвращает имя файла, на который ссылается объект File.

alert($("#file")[0].files[0].name); /* или */ alert(document.getElementById("file").files[0].name);

Пример:

Имена всех выбранных файлов (multiple)

let names = []; for(var i = 0; i < $("#file")[0].files.length; i++)< names.push($("#file")[0].files.item(i).name); >alert(names.join("\r\n"));

Пример:

Получить тип выбранного файла (MIME)

File.type возвращает MIMEтип файла.

alert($("#file")[0].files[0].type); /* или */ alert(document.getElementById("file").files[0].type);

Пример:

Типы всех выбранных файлов (multiple)

let names = []; for(var i = 0; i < $("#file")[0].files.length; i++)< names.push($("#file")[0].files.item(i).type); >alert(names.join("\r\n"));

Пример:

Получить размер выбранного файла

File.size возвращает размер файла в байтах.

Читайте также:  Calc css высота блока

Пример:

Размер всех выбранных файлов (multiple)

$('#btn').click(function() < let size = 0 for(var i = 0; i < $("#file")[0].files.length; i++)< size += $("#file")[0].files.item(i).type; >alert(size); >);

Пример:

Комментарии

Другие публикации

Загрузка файлов на сервер PHP

В статье приведен пример формы и php-скрипта для безопасной загрузки файлов на сервер, возможные ошибки и рекомендации при работе с данной темой.

Загрузка изображений с превью AJAX + PHP + MySQL

В данной статье представлена упрощенная реализация загрузки изображений с превью через AJAX с сохранением в базу данных.

Автоматическое сжатие и оптимизация картинок на сайте

Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет.

Работа с Textarea jQuery

Сборник jQuery приемов с textarea — получить содержимое, вставить значение, подсчет количества символов и строк и т.д.

Работа с cookie в JavaScript

Сookies или куки – это данные в виде пар ключ=значение, которые хранятся в файлах на компьютере пользователя. Для хранимых данных существуют несколько ограничений.

Contenteditable – текстовый редактор

Если добавить атрибут contenteditable к элементу, его содержимое становится доступно для редактирования пользователю, а.

Источник

Загрузка файлов через jQuery AJAX

В преведущей статье был приведен пример отправки файлов через AJAX с помощью плагина «jQuery Form Plugin». Но файлы можно отправить и обычным методом jQuery $.ajax() .

Отправка одного файла

Для примера возьмем поле и элемент div с id=»result» для вывода результата.

Чтобы отправить файл нужно отправить его бинарный данные, для этого есть объект FormData, поддерживается он всеми современными браузерами.

   

Помимо использования formData, в настройках $.ajax нужно указать параметры contentType: false и processData: false т.к. без них файл не отправится.

Код скрипта upload.php

 $input_name = 'file'; // Разрешенные расширения файлов. $allow = array(); // Запрещенные расширения файлов. $deny = array( 'phtml', 'php', 'php3', 'php4', 'php5', 'php6', 'php7', 'phps', 'cgi', 'pl', 'asp', 'aspx', 'shtml', 'shtm', 'htaccess', 'htpasswd', 'ini', 'log', 'sh', 'js', 'html', 'htm', 'css', 'sql', 'spl', 'scgi', 'fcgi', 'exe' ); // Директория куда будут загружаться файлы. $path = __DIR__ . '/uploads/'; $error = $success = ''; if (!isset($_FILES[$input_name])) < $error = 'Файл не загружен.'; >else < $file = $_FILES[$input_name]; // Проверим на ошибки загрузки. if (!empty($file['error']) || empty($file['tmp_name'])) < $error = 'Не удалось загрузить файл.'; >elseif ($file['tmp_name'] == 'none' || !is_uploaded_file($file['tmp_name'])) < $error = 'Не удалось загрузить файл.'; >else < // Оставляем в имени файла только буквы, цифры и некоторые символы. $pattern = "[^a-zа-яё0-9,~!@#%^-_\$\?\(\)\\[\]\.]"; $name = mb_eregi_replace($pattern, '-', $file['name']); $name = mb_ereg_replace('[-]+', '-', $name); $parts = pathinfo($name); if (empty($name) || empty($parts['extension'])) < $error = 'Недопустимый тип файла'; >elseif (!empty($allow) && !in_array(strtolower($parts['extension']), $allow)) < $error = 'Недопустимый тип файла'; >elseif (!empty($deny) && in_array(strtolower($parts['extension']), $deny)) < $error = 'Недопустимый тип файла'; >else < // Перемещаем файл в директорию. if (move_uploaded_file($file['tmp_name'], $path . $name)) < // Далее можно сохранить название файла в БД и т.п. $success = '

Файл «' . $name . '» успешно загружен.

'; > else < $error = 'Не удалось загрузить файл.'; >> > > // Вывод сообщения о результате загрузки. if (!empty($error)) < $error = '

' . $error . '

'; > $data = array( 'error' => $error, 'success' => $success, ); header('Content-Type: application/json'); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit();

Источник

How to Create a Custom File Input with jQuery, CSS3 and PHP

How to create a Custom File Input with jQuery, CSS3 and PHP

We all know that file inputs are very limited in terms of customization and while there are many convoluted plugins with dozens of fallbacks that let you customize them, it’s still a challenge sometimes to get it working. This tutorial will guide you through the process of building a jQuery plugin to replace that ugly looking input with support for multiple files and a simple fallback for old browsers, ahem, IE9-8.

How to create a Custom File Input with jQuery, CSS3 and PHP

[tut demo=”https://onextrapixel.com/examples/custom-file-input-with-jquery-css3-and-php/” download=”https://onextrapixel.com/examples/custom-file-input-with-jquery-css3-and-php/custom-file-input-with-jquery-css3-and-php.zip”]

How to Create a Custom File Input with jQuery, CSS3 and PHP

Setting up the Project

First let’s create a folder customFile and 3 files, jquery.customFile.js , jquery.customFile.css and customFile.html . To get started quickly, grab this HTML template and copy/paste it into your project.

Now that we have everything that we need let’s open our HTML file and add a container and a file input with its label:

Also make sure to give it an id and an array name, such as myfiles[] so the server can retrieve all filenames with the IE fallback that will be covered later.

Next open jquery.customFile.js and setup a basic jQuery plugin boilerplate:

Finally, call the plugin in your markup:

How it Works

To build the custom replacement we’ll need a simple markup structure:

Concept

Clicking the “open” button will trigger a “click” event on the original file input. After choosing a file the original input triggers a “change” event, where we’ll set the value of the input by accessing the file array if the file API is supported, or by accessing the original value otherwise.

Building the Plugin

First we need to test the browser for multiple support. The easiest way is to create an input and check if it has a multiple property available otherwise the browser doesn’t support multiple files. We also need to check if the browser is IE for some fixes later on. This code can be moved outside of the plugin since it doesn’t depend on the element itself.

// Browser supports HTML5 multiple file? var multipleSupport = typeof $('')[0].multiple !== 'undefined', isIE = /msie/i.test( navigator.userAgent ); // simple but not super secure.

Now let’s create the elements needed for the replacement. IE has tough security measures that prevent the filename from being retrieved if the input is triggered externally so we’ll be using a label instead of a button . By triggering the event on the label we can work around this issue.

The type=»button» attribute is needed for consistency, to prevent some browsers from submitting the form.

Next, let’s “get rid” of the original input. Instead of hiding it, let’s remove from the viewport by shifting it to the left, that way we can still use it even if it’s not visible; this is useful to trigger events that may be problematic if the input is literally hidden.

Finally let’s append our new elements to the DOM:

$wrap.insertAfter( $file ).append( $file, $input, ( isIE ? $label : $button ) );

At this point you should have something that looks like this in a decent browser; we’ll take care of IE later.

Step 1

Attaching the Events

The very first thing we need to do is to prevent the original input from gaining focus, as well as the newly created button. Only the text input should be able to receive focus.

$file.attr('tabIndex', -1); $button.attr('tabIndex', -1);

Let’s trigger the click event on the button to open the dialog. In IE, since there’s no real button, the label should already trigger the dialog without extra work.

The focus event needs to be triggered on some browsers so the click event works properly. If you try clicking “open” in your browser at this point it should open the file dialog.

Now we can use the change event that is triggered after choosing a file to fill the value of the text input with the chosen file(s).

$file.change(function() < var files = [], fileArr, filename; // If multiple is supported then extract // all filenames from the file array if ( multipleSupport ) < fileArr = $file[0].files; for ( var i = 0, len = fileArr.length; i < len; i++ ) < files.push( fileArr[i].name ); >filename = files.join(', '); // If not supported then take the value // and remove the path to show only the filename > else < filename = $file.val().split('\\').pop(); >$input.val( filename ) // Set the value .attr('title', filename) // Show filename in title tootlip .focus(); // Regain focus >);

Improving Usability

Everything is working well so far but there are some things that we can do to improve the usability and overall behavior of our new replacement.

  • Trigger the blur event on the original input when the replacement loses focus.
  • Open the dialog when user presses “enter” on the text input except IE (due to security limitations it won’t work).
  • Delete files with “backspace” or “delete”, otherwise the user is forced to open the dialog and press “cancel” to clear the input.
$input.on(< blur: function() < $file.trigger('blur'); >, keydown: function( e ) < if ( e.which === 13 ) < // Enter if ( !isIE ) < $file.trigger('click'); >> else if ( e.which === 8 || e.which === 46 ) < // Backspace & Del // On some browsers the value is read-only // with this trick we remove the old input and add // a clean clone with all the original events attached $file.replaceWith( $file = $file.clone( true ) ); $file.trigger('change'); $input.val(''); >else if ( e.which === 9 ) < // TAB return; >else < // All other keys return false; >> >);

Fallback for Old Browsers

The easiest fallback to allow multiple files is to create multiple inputs. When a file is chosen we create a new input and when the input is cleared, we remove it.

The following code goes after the plugin since it’s meant to be applied to all custom file inputs. Here we need to use on to delegate the event for future inputs that don’t exist yet.

if ( !multipleSupport ) < $( document ).on('change', 'input.customfile', function() < var $this = $(this), // Create a unique ID so we // can attach the label to the input uniqId = 'customfile_'+ (new Date()).getTime(); $wrap = $this.parent(), // Filter empty input $empty = $wrap.siblings().find('.customfile-filename') .filter(function()< return !this.value >), $file = $(''); // 1ms timeout so it runs after all other events // that modify the value have triggered setTimeout(function() < // Add a new input if ( $this.val() ) < // Check for empty field to prevent // creating new inputs when changing files if ( !$empty.length ) < $wrap.after( $file ); $file.customFile(); >// Remove and reorganize inputs > else < $empty.parent().remove(); // Move the input so it's always last on the list $wrap.appendTo( $wrap.parent() ); $wrap.find('input').focus(); >>, 1); >); >

Customizing the Appearance

Everything must be working at this point so let’s spice it up with some styles:

/* It's easier to calculate widths * with border-box layout */ .customfile-container * < box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; font: normal 14px Arial, sans-serif; /* Global font to use ems with precision */ >.customfile-container < width: 300px; background: #FFF2B8; padding: 1em; >.customfile-container label:first-child < width: 100px; display: block; margin-bottom: .5em; font: bold 18px Arial, sans-serif; color: #333; >.customfile-wrap < position: relative; padding: 0; margin-bottom: .5em; >.customfile-filename, .customfile-upload < margin: 0; padding: 0; >.customfile-filename < width: 230px; padding: .4em .5em; border: 1px solid #A8A49D; border-radius: 2px 0 0 2px; box-shadow: inset 0 1px 2px rgba(0,0,0,.2); >.customfile-filename:focus < outline: none; >.customfile-upload < display: inline-block; width: 70px; padding: .4em 1em; border: 1px solid #A8A49D; background: #ddd; border-radius: 0 2px 2px 0; margin-left: -1px; /* align with input */ cursor: pointer; background: #fcfff4; background: -moz-linear-gradient(top, #fcfff4 0%, #e9e9ce 100%); background: -webkit-linear-gradient(top, #fcfff4 0%, #e9e9ce 100%); background: -o-linear-gradient(top, #fcfff4 0%, #e9e9ce 100%); background: -ms-linear-gradient(top, #fcfff4 0%, #e9e9ce 100%); background: linear-gradient(to bottom, #fcfff4 0%, #e9e9ce 100%); >.customfile-upload:hover < background: #fafafa; box-shadow: 0 0 2px rgba(0,0,0,.2); >.customfile-upload::-moz-focus-inner < /* Fix firefox padding */ padding: 0; border: 0; >

Go ahead and customize the CSS to create your own look.

Retrieving the Files on the Server

First, wrap your input in a form and add a submit button:

Then, we can get all the filenames and print them out in test.php :

Since we’re using an array name myfiles[] , the server will retrieve all files even when the fallback is being used. You can read more about this in the PHP manual on Uploading Multiple Files.

The plugin has been tested on IE9-8 and all modern browsers. Grab the full code or play with the demo below.

[tut demo=”https://onextrapixel.com/examples/custom-file-input-with-jquery-css3-and-php/” download=”https://onextrapixel.com/examples/custom-file-input-with-jquery-css3-and-php/custom-file-input-with-jquery-css3-and-php.zip”]

Conclusion

Without much effort file inputs are fairly easy to customize. The fallback is obviously not ideal but it works and it’s simple to maintain without introducing hundreds of lines of code, or other technologies like Flash, Silverlight, etc…

If you have any suggestions please leave a comment below.

Источник

Jquery input file php

*

Частная коллекция качественных материалов для тех, кто делает сайты

  • Creativo.one2000+ уроков по фотошопу
  • Фото-монстр300+ уроков для фотографов
  • Видео-смайл200+ уроков по видеообработке
  • Жизнь в стиле «Кайдзен» Техники и приемы для гармоничной и сбалансированной жизни

В этой рубрике Вы найдете уроки по Javascript библиотеке jQuery.

Анимация набора текста на jQuery

Сегодня мы бы хотели вам рассказать о библиотеке TypeIt — бесплатном jQuery плагине. С её помощью можно имитировать набор текста. Если всё настроить правильно, то можно добиться очень реалистичного эффекта.

Временная шкала на jQuery

Заметка: Перезагрузка и редирект на JavaScript

Быстрая заметка, где вы сможете найти парочку JS сниппетов для перезагрузки и перенаправления пользователей через JavaScript.

Рисуем диаграмму Ганта

AJAX и PHP: загрузка файла

Stimed — стили в зависимости от времени суток

Интересная библиотека с помощью которой можно задать определённым элементам страницы особые стили в зависимости от времени суток.

Источник

Оцените статью