Jquery file upload


Ура! Еще один, свеженький… чем он лучше других?

Jquery file upload

а) Новенький! Всегда, кто берется что-то делать, то обычно смотрит: есть ли в этом смысл, и если есть — делает это.
б) Красивенький! Можно не точить, а ставить из коробки. Основан на Bootstrap’е и иконках Glyphicons
в) Само собой мультиселект файлов, Drag&drop, прогрессбар и превьюшки фотографий.
г) Поддержка кросдоменного соединения, докачка и ресайз фоток на стороне клиента.
д) Готов для любой платформы сервера (PHP, Python, Ruby on Rails, Java, Node.js, и тому подобное.)

blueimp.github.com/jQuery-File-Upload

Поддержка браузеров:

github.com/blueimp/jQuery-File-Upload/wiki/Browser-support

Быстрое подключение

Доступно две версии плагина. В Bootstrap’е и в Jquery UI
Если вам приспичит полностью переделать интерфейс, то вот голая версия плагина


Подробнее

Как настроить плагин?

Используем jQuery File Upload (версию UI) для PHP.

То что идет в коробке с плагином полностью работоспособно, остается только залить это себе на сервер.

Качаем, распаковываем, заливаем распакованное на наш сервер ( папку можно переименовывать ).
Пробуем запустить демо страницу для проверки работоспособности.

Учтите, что заливка файлов работает для всех, и эти же файлы могут быть скачаны так же всеми. Самый простой способ защиты — поставить пароль на папку с залитыми файлами через .htaccess.

Используем jQuery File Upload (версию UI) для Google App Engine

Качаем плагин, распаковываем, редактируем файл app.yaml для подмены «jquery-file-upload» на ваш собственный App ID. Заливаем в server/gae-python или server/gae-go ( в зависимости от среды разработки) как ваш App Engine instance.
Залейте папку jQuery-File-Upload (корневую) на любой сервер, после редактирования поля form action target на ваш урл к вашему App Engine instance.

Использование jQuery File Upload (версию UI) с Node.js

Вы можете установить пример на Node.js на ваш сервер через npm.
npm install blueimp-file-upload-node

Запуск сервиса:
./node_modules/blueimp-file-upload-node/server.js

Качаем архив с плагином, распаковываем, правим index.html и настраиваем путь в form action на ваш Node.js ( типа «localhost:8080»).
Вы можете залить папку с проектом ( без ненужных файлов) на любой сервер и использовать его как интерфейс для вашего сервиса по заливке файлов на Node.js.


Использование jQuery File Upload (версию UI) с другими платформами

Подробнее здесь github.com/blueimp/jQuery-File-Upload/wiki/Setup

Ps. рекомендации с комментариев

«при связке Apache+PHP нужно дать веб-серверу право на запись в папки files и thumbnails (в Ubuntu его зовут, например www-data). Для проверки на работоспособность можно просто выставить ‘777’ на эти папки, но это потенциально небезопасный путь.

В противном случае появляется обилие UNEXPECTED TOKEN всех мастей. » — irsick

habr.com

JqueryFileUpload

This module is a ProcessWire implementation of the awesome Blueimp jQuery File Upload plugin. Server-side, the module provides a custom uploads handler enabling you to perform various tasks with ease. The module is an interface of the feature-rich Ajax File Uploads widget provided by the jQuery File Upload plugin.

The module is completely customisable and can be used both in the front- and backend (e.g. in third-party module).

Security


The module has been written with security in mind and makes no assumptions about any client-side validation.


stead, the module provides robust server-side validation of uploaded files. Server-side, no Ajax requests are honoured unless specifically set via configurable options server-side. This means that client-side requests to upload, delete and list files are not executed unless allowed server-side. By default, files are uploaded to a non-web-accessible (system) folder and files previously uploaded on the server are not sent back for display unless that setting is enabled. However, developers are still strongly advised to implement any other feasible measures to guard against malicious uploads, especially if allowing frontend uploading. For instance, developers can use native ProcessWire checks to limit access to the widget (e.g. only allowing uploads by registered/logged-in users).

Demo


A short demo can be found here.

Features


  • Fast Ajax uploads.
  • Client and server-side validation.
  • Client-side image resizing (highly configurable options).
  • Beautiful touch-responsive image gallery preview.
  • Audio and video previews pre-upload.
  • Chunked and resumable file uploads (currently client-side only; see notes section).
  • Drag and drop support.
  • Copy and paste support (Google Chrome only).
  • Progress bars.
  • Cross-domain uploads.
  • Single or multiple uploads.
  • Delete uploaded files.

Options


JqueryFileUpload implements all the options that come with the jQuery File Upload plugin. In addition, it includes the following custom server-side options:


  • showUploaded: Whether to show uploaded files (default is false).
  • uploadsDeletable: Whether clients can delete uploads (default is false).
  • disableUploads: If set to true, the widget becomes a file lister only. Default is false.
  • responseType: If set to 1, module returns a JSON response to valid Ajax requests. If 2, it returns an Array. This can be useful if further processing is needed, e.g. in a module, before outputting final JSON. Default is to return a JSON response.
  • privateUploadsDir: The non-web-accessible folder to save uploads to. If showUploaded is set to false, this (system) directory is used for saving uploads.
  • thumbsPrivateDir: Set a non-web-accessible folder for thumbnails.
  • uploadsDir: Set a web-accessible folder to upload images to. Default is under /sites/. Needed if displaying uploaded images.
  • thumbsDir: Set a web-accessible folder for thumbnails. Needed if displaying uploaded images.
  • setMaxFiles: Maximum number of files per upload. Default is 30.
  • setOverwrite: If to overwrite files in case of name-collision. Default is false.
  • useCustomForm: Whether to use a custom form + action buttons for uploads + upload actions.

  • enableDropZone: Disable drop-zone features of the widget.
  • showGallery: Whether to enable the widget to display uploaded images in a (blueimp) gallery.
  • thumbsWidth: Set the width for image thumbnails: Default is 100.
  • thumbsHeight: Set the height for image thumbnails. Defaults to 75.
  • createThumb: Whether to create image thumbnails for uploads. Default is false.
  • allowedImageMimeTypes: Array of allowed image mime types: Default is array(‘image/gif’, ‘image/jpeg’, ‘image/png’).
  • imageTypeConstants: Array of allowed image type constants. Default is array(‘gif’ => IMAGETYPE_GIF, ‘jpeg’ => IMAGETYPE_JPEG, ‘jpg’ => IMAGETYPE_JPEG, ‘png’ => IMAGETYPE_PNG).
  • allowedNonImageMimeTypes: Array of allowed non-image files mime types. Default is array(‘application/pdf’, ‘audio/mpeg’, ‘video/mp4’).
  • noGallery: Don’t output the plugin’s gallery scripts and CSS. For use in the two scripts and two styles methods listed below. Also see example usage below.
  • noIframeTransport: Same as above; not to output iframe transport script.
  • noResize: Same as above; not to output client-side image resizing script.

  • noAudioPreview: Same as above; not to output script that enables preview of audio files pre-uploading them.
  • noVideoPreview: Same as above; not to output script that enables preview of video files pre-uploading them.
  • useCustomScript: Same as above; not to output the module’s main Javascript file JqueryFileUpload.js to instead use your own.
  • useCustomStyle: Same as above; not to output the module’s main CSS file JqueryFileUpload.css to instead use your own.
  • unzipFiles: Whether to decompress zip files after upload. contents will then be listable if listing. The zip file is deleted after decompression. Please note unzip is only allowed in the backend.

How to Install


Install as any other ProcessWire module.

How to Use


API


Developers will mainly directly interact with the following methods:

render($options)

This method renders the markup of the full uploads widget. The method accepts one argument, an array of $options. You can by-pass this method and instead use your own custom form. It will take relevant custom options listed above including uploadsDeletable (controls output of file widgets delete buttons) as well as some native jQuery File Upload options such as paramName.


dividual bits of the form can also be output separately using various internal methods (for instance renderAddUploadsButton()). Have a look at the code for more details. Note that in the backend, render() does not output form tags. Instead, it expects the developer to wrap its markup within a ProcessWire generated form. The form must be given the ID fileupload (unless you will be implementing your own script to talk to the jQuery File Upload plugin; see below).

processJFUAjax($options)

This is a very important method that controls client-generated Ajax requests to your server. By default, its default array of $options are very restrictive. Think carefully before overriding any of them. For instance, overriding the uploads directory, showing a list of uploaded files or allowing deletion of uploads. It takes one array argument, $options. If you prefer, you can use your own uploads handler instead of using this method.

configsJFU($options)

We use this method to pass configuration options to jQuery File Upload plugin. It returns a JSON string if called in the frontend and populates ProcessWire’s $config->js(). If called in the backend. In the frontend, you need to call and output the method before the page is rendered (see example usage below). The method’s $options argument must be an array. Any of the jQuery File Upload plugin options can be passed to it as well as the custom options showUploaded and showGallery.


renderJFUScripts($options)

This method’s output can be echoed in the

or just before the closing </body> in your HTML. It outputs the necessary Javascript jQuery File Upload files, i.e. using <script></script> tags. The method is therefore suitable if you are using this module in the frontend. If not needing certain features of jQuery File Upload (e.g. client-side image resizing), pass it relevant options to suppress output of the related script(s). For instance, if you will not need pre-upload video previews, you can tell the script as follows: renderJFUScripts(array(‘noVideoPreview’)).

configJFUScripts($options)

This method is equivalent to renderJFUScripts() except that it uses ProcessWire’s $config->scripts->add() to add scripts to the DOM. Hence, the method is suited for cases where the module is being used in the backend. It accepts similar options to its sibling method. For instance, configJFUScripts(array(‘useCustomScript’)) will allow you to implement your own script to talk to jQuery File Uploads plugin.

renderJFUStyles($options)

This method’s output should be echoed in the


in your HTML. It outputs CSS tags. It takes one argument, $options. To disable outputting the image gallery CSS, pass it the option as follows: renderJFUStyles(array(‘noGallery’)).

configJFUStyles($options)

This method is equivalent to renderJFUStyles() except that it uses ProcessWire’s $config->styles->add() to add styles to the DOM. Hence, the method is suited for cases where the module is being used in the backend. It accepts the same options as its counterpart method. For example, to use custom CSS to style the file uploads widget, pass an option as follows: configJFUStyles(array(‘useCustomStyle’)).

Example usage in a template file (frontend)

 // call the module $jfu = $modules->get('JqueryFileUpload');  // if we got an ajax request deal with it before page is rendered if ($config->ajax) { 	// server-side options to send to the ajax handler 	$ajaxOptions = array( 		'uploadsDeletable' => 1,// disable attempts to delete upload (this is already the default but included here just as an example) 		'showUploaded' => 1,// don't send back response listing uploads 		//'disableUploads' => true// disable uploads @note: matches similar setting in render() 	);  	// action the ajax request 	echo $jfu->processJFUAjax($ajaxOptions); }  // example options to send to jQuery File Upload plugin. // The plugin has its own set of defaults.  

re we override some of them $jfuOptions = array( 'imageMaxWidth' => 1280,// limit image width (will be resized) 'imageMaxHeight' => 768,// limit image (ditto) 'prependFiles' => true,// add new uploads to the top of the file listing // allow to resize images. Default is true, i.e. to disable. // We set this to false if we want IMAGES TO BE RESIZED CLIENT-SIDE BEFORE UPLOAD 'disableImageResize' => false, // custom option for this module: whether to show list of files currently on the server 'showUploaded' => true,// if false, will stop the widget from sending requests to list uploads already on the server ); // prepare configuration options to send to the plugin // outside the ProcessWire Admin the method configsJSU() returns a JSON string // Otherwise, it populates the $config->js() array $jfuConfig = $jfu->configsJFU($jfuOptions); // options to pass to the render() method $options = array( // useful for allowing uploads to one group of users and not the other (e.g. registered versus non-registered) // for security, we also pass this option to processJFUAjax($options) to reject any upload attempts //'disableUploads' => true, );
 <head> 	<meta http-equiv="content-type" content="text/html; charset=utf-8"> 	<title><?php echo $page->title; ?></title>  	<!-- echo this modules CSS styles. This is optional; you are free to use your own CSS styles --> 	<?php echo $jfu->renderJFUStyles(); ?>  	<!-- Include the usual suspects. We need both for the module to work --> 	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> 	<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>  	<!-- Output the plugins Javascript configurations before the page is fully rendered. 		@note: These are the configs we prepared earlier in the PHP block --> 	<script type="text/javascript">var config = <?php echo $jfuConfig; ?>;</script>  	<!-- Output the scripts needed to make the widget work. We could also output these just before we close &lt;/body&gt; 		In the first commented out example, we tell the method renderJFUScripts() not to ouput certain scripts 		since we will not be using them, e.g. we will not be showing previews of videos queued for uploading 		In the second active example, we output all the scripts --> 	<?php //echo $jfu->renderJFUScripts(array('noGallery','noIframeTransport', 'noResize','noAudioPreview', 'noVideoPreview')); ?> 	<?php echo $jfu->renderJFUScripts(); ?>  	<!-- This is a custom CSS file for this page --> 	<link rel="stylesheet" type="text/css" href="<?php echo $config->urls->templates?>styles/main.css">  </head> <body> <div id="wrapper"> 	<h1><?php echo $page->title; ?></h1> 	<?php 		// echo the file widget's markup using the render() method and passing to it any options we set earlier 		echo $jfu->render($options); 		// can also render without $options if happy with the defaults 		#echo $jfu->render(); 	?>  	</div> &lt;/body&gt;

Uninstall


Uninstall like any other third-party ProcessWire module.

Notes


  • Currently, chunked file uploads have not been implemented on the server-side. You would need to use a custom uploads handler for this.

Support forum


Support

Changelog


Version 0.0.8
  1. Made the method to process zip archives public so that it can be used with other modules/classes.
Version 0.0.7
  1. Added option to unzip uploaded ZIP archives (works only if used in backend).
  2. Refreshed upload widget look and style.

Changelog


Version 0.0.6
  1. Added support for SVGs.
Version 0.0.5
  1. Fixed a typo in the default setting for maxFileSize.
Version 0.0.4
  1. Fixed minor bug introduced in last version’s commit that caused some images not to be displayed in the gallery.
Version 0.0.3
  1. Fixed an issue that caused duplicates in image gallery.
  2. Some minor enhancements.
Version 0.0.2
  1. Additional CSS added.
  2. filesContainer value now configurable.
  3. Added a thumbsPrivateDir option.
  4. Response type from module can now be either JSON or an Array (for further processing, say, in a module).
Version 0.0.1
  1. Initial release.

License


Released under the MIT license.

Credits

modules.processwire.com

1. Plugin Demo and Features

1.1 Video Demo #1 – Single & Multiple Files Upload

1.2 Video Demo #2 – Drag & Drop File Upload

1.3 Features

• Multiple file upload:
Allows to select multiple files at once and upload them simultaneously.
• Drag & Drop support:
Allows to upload files by dragging them from your desktop or filemanager and dropping them on your browser window.
• Upload progress bar:
Shows a progress bar indicating the upload progress for individual files and for all uploads combined.
• Cancelable uploads:
Individual file uploads can be canceled to stop the upload progress.
• Resumable uploads:
Aborted uploads can be resumed with browsers supporting the Blob API.
• Chunked uploads:
Large files can be uploaded in smaller chunks with browsers supporting the Blob API.
• Client-side image resizing:
Images can be automatically resized on client-side with browsers supporting the required JS APIs.
• Preview images, audio and video:
A preview of image, audio and video files can be displayed before uploading with browsers supporting the required APIs.
• No browser plugins (e.g. Adobe Flash) required:
The implementation is based on open standards like HTML5 and JavaScript and requires no additional browser plugins.
• Graceful fallback for legacy browsers:
Uploads files via XMLHttpRequests if supported and uses iframes as fallback for legacy browsers.
• HTML file upload form fallback:
Allows progressive enhancement by using a standard HTML file upload form as widget element.
• Cross-site file uploads:
Supports uploading files to a different domain with cross-site XMLHttpRequests or iframe redirects.
• Multiple plugin instances:
Allows to use multiple plugin instances on the same webpage.
• Customizable and extensible:
Provides an API to set individual options and define callBack methods for various upload events.
• Multipart and file contents stream uploads:
Files can be uploaded as standard “multipart/form-data” or file contents stream (HTTP PUT file upload).
• Compatible with any server-side application platform:
Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.

2. Basic Plugin Setup

2.1 HTML Setup

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jQuery File Upload Example</title> </head> <body> <input id="fileupload" type="file" name="files[]" data-url="server/php/" multiple> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="js/vendor/jquery.ui.widget.js"></script> <script src="js/jquery.iframe-transport.js"></script> <script src="js/jquery.fileupload.js"></script> <script> $(function () {  $('#fileupload').fileupload({  dataType: 'json',  done: function (e, data) {  $.each(data.result.files, function (index, file) {  $('<p/>').text(file.name).appendTo(document.body);  });  }  }); }); </script> </body> </html> 

Response and data type

The example above sets the dataType option to json, expecting the server to return a JSON response for each uploaded file. However it’s also possible to handle HTML content types as response or any other dataType that you can handle in your done handler.

2.2 Display Upload Progress

The fileupload plugin triggers progress events for both individual uploads (progress) and all running uploads combined (progressall). Event handlers can be set via the event binding mechanism or as widget options.

 $('#fileupload').fileupload({  /* ... */  progressall: function (e, data) {  var progress = parseInt(data.loaded / data.total * 100, 10);  $('#progress .bar').css(  'width',  progress + '%'  );  } }); 

The previous code assumes a progress node with an inner element that displays the progress status via its width percentage:

 <div id="progress">  <div class="bar" style="width: 0%;"></div> </div> 

The inner element should have a different background color than the container node, set via CSS and needs a height applied:

 .bar {  height: 18px;  background: green; } 

2.3 Tie a file to an element node during the life cycle of an upload

Often, you will display a file to upload in an element node. This can be done in the add callback.

To be able to refer to the same element node in other callbacks related to the upload, you can make use of the context option (which is actually an option of jquery.ajax):

 $(function () {  $('#fileupload').fileupload({  dataType: 'json',  add: function (e, data) {  data.context = $('

').text('Uploading...').appendTo(document.body); data.submit(); }, done: function (e, data) { data.context.text('Upload finished.'); } }); });

2.4 Start Uploads with a button click

Based on the previous example, it’s possible to start uploads on the click of a button instead of automatically:

 $(function () {  $('#fileupload').fileupload({  dataType: 'json',  add: function (e, data) {  data.context = $('

3. Requirements

3.1 Mandatory Requirements

• jQuery v. 1.6+
• jQuery UI widget factory v. 1.9+ (included)
• jQuery Iframe Transport plugin (included)

The jQuery UI widget factory is a requirement for the basic File Upload plugin, but very lightweight without any other dependencies from the jQuery UI suite. The jQuery Iframe Transport is required for browsers without XHR file upload support.

3.2 Optional Requirements

• JavaScript Templates engine v. 2.5.4+
• JavaScript Load Image library v. 1.13.0+
• JavaScript Canvas to Blob polyfill v. 2.1.1+
• blueimp Gallery v. 2.15.1+
• Bootstrap v. 3.2.0+
• Glyphicons

The JavaScript Templates engine is used to render the selected and uploaded files for the Basic Plus UI and jQuery UI.

The JavaScript Load Image library and JavaScript Canvas to Blob polyfill are required for the image previews and resizing functionality.

The blueimp Gallery is used to display the uploaded images in a lightbox.

The user interface of all versions except the jQuery UI version is built with Bootstrap and icons from Glyphicons.

4. Browsers

4.1 Desktop Browsers

The File Upload plugin is regularly tested with the latest browser versions and supports the following minimal versions:

• Google Chrome
• Apple Safari 4.0+
• Mozilla Firefox 3.0+
• Opera 11.0+
• Microsoft Internet Explorer 6.0+
• Microsoft Edge

4.2 Mobile Browsers

The File Upload plugin has been tested with and supports the following mobile browsers:

• Apple Safari on iOS 6.0+
• Google Chrome on iOS 6.0+
• Google Chrome on Android 4.0+
• Default Browser on Android 2.3+
• Opera Mobile 12.0+

5. Conclusion

To conclude, file upload with jQuery can be easily adapted to your websites using the plugin we presented and its’ features. You can find this plugin on GitHub following the link https://github.com/blueimp/jQuery-File-Upload. It also has detailed information on the plugin useage and a live demo. However, if you feel that you are searching for something else Kendo UI has another solution for file uploads that you can find here.

www.webcodegeeks.com

For PHP, look for https://developer.hyvor.com/php/image-upload-ajax-php-mysql

HTML

<html> <head>  <title>Image Upload with AJAX, PHP and MYSQL</title> </head> <body> <form onsubmit="submitForm(event);">  <input type="file" name="image" id="image-selecter" accept="image/*">  <input type="submit" name="submit" value="Upload Image"> </form> <div id="uploading-text" style="display:none;">Uploading...</div> <img id="preview"> </body> </html> 

JAVASCRIPT

var previewImage = document.getElementById("preview"),   uploadingText = document.getElementById("uploading-text");  function submitForm(event) {  // prevent default form submission  event.preventDefault();  uploadImage(); }  function uploadImage() {  var imageSelecter = document.getElementById("image-selecter"),  file = imageSelecter.files[0];  if (!file)   return alert("Please select a file");  // clear the previous image  previewImage.removeAttribute("src");  // show uploading text  uploadingText.style.display = "block";  // create form data and append the file  var formData = new FormData();  formData.append("image", file);  // do the ajax part  var ajax = new XMLHttpRequest();  ajax.onreadystatechange = function() {  if (this.readyState === 4 && this.status === 200) {  var json = JSON.parse(this.responseText);  if (!json || json.status !== true)   return uploadError(json.error);   showImage(json.url);  }  }  ajax.open("POST", "upload.php", true);  ajax.send(formData); // send the form data } 

PHP

<?php $host = 'localhost'; $user = 'user'; $password = 'password'; $database = 'database'; $mysqli = new mysqli($host, $user, $password, $database);    try {  if (empty($_FILES['image'])) {  throw new Exception('Image file is missing');  }  $image = $_FILES['image'];  // check INI error  if ($image['error'] !== 0) {  if ($image['error'] === 1)   throw new Exception('Max upload size exceeded');   throw new Exception('Image uploading error: INI Error');  }  // check if the file exists  if (!file_exists($image['tmp_name']))  throw new Exception('Image file is missing in the server');  $maxFileSize = 2 * 10e6; // in bytes  if ($image['size'] > $maxFileSize)  throw new Exception('Max size limit exceeded');   // check if uploaded file is an image  $imageData = getimagesize($image['tmp_name']);  if (!$imageData)   throw new Exception('Invalid image');  $mimeType = $imageData['mime'];  // validate mime type  $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];  if (!in_array($mimeType, $allowedMimeTypes))   throw new Exception('Only JPEG, PNG and GIFs are allowed');   // nice! it's a valid image  // get file extension (ex: jpg, png) not (.jpg)  $fileExtention = strtolower(pathinfo($image['name'] ,PATHINFO_EXTENSION));  // create random name for your image  $fileName = round(microtime(true)) . mt_rand() . '.' . $fileExtention; // anyfilename.jpg  // Create the path starting from DOCUMENT ROOT of your website  $path = '/examples/image-upload/images/' . $fileName;  // file path in the computer - where to save it   $destination = $_SERVER['DOCUMENT_ROOT'] . $path;   if (!move_uploaded_file($image['tmp_name'], $destination))  throw new Exception('Error in moving the uploaded file');   // create the url  $protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';  $domain = $protocol . $_SERVER['SERVER_NAME'];  $url = $domain . $path;  $stmt = $mysqli -> prepare('INSERT INTO image_uploads (url) VALUES (?)');  if (  $stmt &&  $stmt -> bind_param('s', $url) &&  $stmt -> execute()  ) {  exit(  json_encode(  array(  'status' => true,  'url' => $url  )  )  );  } else   throw new Exception('Error in saving into the database');  } catch (Exception $e) {  exit(json_encode(  array (  'status' => false,  'error' => $e -> getMessage()  )  )); } 

stackoverflow.com

jQuery File upload plugin has the following features.

  • Single File Upload
  • Multiple file Upload (Drag & Drop)
  • Sequential file upload
  • File Restrictions
  • Localization (Multi-language)
  • Sending Form Data
  • Adding HTML elements to progressbar
  • Custom UI
  • Upload Events
  • Delete / Download Uploaded files
  • Image Preview
  • Show previous uploads

1).Single File Upload

With the below configuration, plugin allows only single file upload (without drag & drop).
Source:

 $("#singleupload").uploadFile({ url:"upload.php", multiple:false, dragDrop:false, maxFileCount:1, fileName:"myfile" }); 


2).Multiple file Upload (Drag &Drop)

With the below configuration, plugin supports multiple file upload with drag & drop.
Source:

 $("#multipleupload").uploadFile({ url:"upload.php", multiple:true, dragDrop:true, fileName:"myfile" }); 


3).Sequential file Upload

With the below configuration, plugin uploads the file sequentially. you can control number of active uploads with sequentialCount.
Source:

 $("#sequentialupload").uploadFile({ url:"upload.php", fileName:"myfile", sequential:true, sequentialCount:1	 }); 


4).Upload with File Restrictions

With the below configuration, plugin allows only specific file types.
Source:

 $("#restrictupload1").uploadFile({ url:"upload.php", fileName:"myfile", acceptFiles:"image/*" }); 

Output:

With the below configuration, plugin allows only files lesser than the specified size/count.
Source:

 $("#restrictupload2").uploadFile({ url:"upload.php", fileName:"myfile", maxFileCount:3, maxFileSize:100*1024 }); 

Output:


5).Localization

With the below configuration, you can change all the plugin strings.
Source:

  $("#localupload").uploadFile({ 	url:"upload.php", 	fileName:"myfile", 	dragDropStr: "<span><b>Faites glisser et déposez les fichiers</b></span>",  abortStr:"abandonner", 	cancelStr:"résilier", 	doneStr:"fait", 	multiDragErrorStr: "Plusieurs Drag &amp; Drop de fichiers ne sont pas autorisés.", 	extErrorStr:"n'est pas autorisé. Extensions autorisées:", 	sizeErrorStr:"n'est pas autorisé. Admis taille max:", 	uploadErrorStr:"Upload n'est pas autorisé", 	uploadStr:"Téléchargez" 	}); 

Output:


6).Sending Form Data

With the below configuration, plugin sends the form data with every file uploaded. form data can be accessed at server side using $_POST.
Source:

 $("#formdata1").uploadFile({ url:"upload.php", fileName:"myfile", formData: {"name":"Ravi","age":31}	 }); 

Output:

With the below configuration, plugin sends dynamic form data with every file upload. For example, if you want to send updated ‘input’ value with the uploaded file.
Source:

 $("#formdata2").uploadFile({ url:"upload.php", fileName:"myfile", dynamicFormData: function() { 	var data ={ location:"INDIA"} 	return data; } }); 

Output:


7).Add extra HTML Elements

With the below configuration,plugin allows to add extra HTML elements (input,textarea,select) to status bar.
Source:

 var extraObj = $("#extraupload").uploadFile({ url:"upload.php", fileName:"myfile", extraHTML:function() {  	var html = "<div><b>File Tags:</b><input type='text' name='tags' value='' /> <br/>"; 		html += "<b>Category</b>:<select name='category'><option value='1'>ONE</option><option value='2'>TWO</option></select>"; 		html += "</div>"; 		return html; 		 }, autoSubmit:false }); $("#extrabutton").click(function() {  	extraObj.startUpload(); }); 

Output:


8).Custom UI

Using the below configuration, you can design your own progress bar.
Source:

 var count=0; 	$("#customupload1").uploadFile({ 	url:"upload.php", 	fileName:"myfile", 	showFileCounter:false, 	customProgressBar: function(obj,s) 		{ 			this.statusbar = $("<div class='ajax-file-upload-statusbar'></div>");  this.preview = $("<img class='ajax-file-upload-preview' />").width(s.previewWidth).height(s.previewHeight).appendTo(this.statusbar).hide();  this.filename = $("<div class='ajax-file-upload-filename'></div>").appendTo(this.statusbar);  this.progressDiv = $("<div class='ajax-file-upload-progress'>").appendTo(this.statusbar).hide();  this.progressbar = $("<div class='ajax-file-upload-bar'></div>").appendTo(this.progressDiv);  this.abort = $("<div>" + s.abortStr + "</div>").appendTo(this.statusbar).hide();  this.cancel = $("<div>" + s.cancelStr + "</div>").appendTo(this.statusbar).hide();  this.done = $("<div>" + s.doneStr + "</div>").appendTo(this.statusbar).hide();  this.download = $("<div>" + s.downloadStr + "</div>").appendTo(this.statusbar).hide();  this.del = $("<div>" + s.deleteStr + "</div>").appendTo(this.statusbar).hide();    this.abort.addClass("custom-red");  this.done.addClass("custom-green"); 			this.download.addClass("custom-green");   this.cancel.addClass("custom-red");  this.del.addClass("custom-red");  if(count++ %2 ==0) 	 this.statusbar.addClass("even");  else  			this.statusbar.addClass("odd");  			return this; 			 		}	 	}); 

Output:


9).Upload Events

Below are the different callback events. Source:

 $("#eventsupload").uploadFile({ url:"upload.php", multiple:true, fileName:"myfile", returnType:"json", onLoad:function(obj) { 		$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Widget Loaded:"); }, onSubmit:function(files) { 	$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Submitting:"+JSON.stringify(files)); 	//return false; }, onSuccess:function(files,data,xhr,pd) {  	$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Success for: "+JSON.stringify(data)); 	 }, afterUploadAll:function(obj) { 	$("#eventsmessage").html($("#eventsmessage").html()+"<br/>All files are uploaded"); 	  }, onError: function(files,status,errMsg,pd) { 	$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Error for: "+JSON.stringify(files)); }, onCancel:function(files,pd) { 		$("#eventsmessage").html($("#eventsmessage").html()+"<br/>Canceled files: "+JSON.stringify(files)); } }); 

Output:


10).Delete/Download Files

With the below configuration, plugin supports File download and File delete features. Source:

 $("#deleteupload").uploadFile({url: "upload.php", dragDrop: true, fileName: "myfile", returnType: "json", showDelete: true, showDownload:true, statusBarWidth:600, dragdropWidth:600, deleteCallback: function (data, pd) {  for (var i = 0; i < data.length; i++) {  $.post("delete.php", {op: "delete",name: data[i]},  function (resp,textStatus, jqXHR) {  //Show Message	  alert("File Deleted");  });  }  pd.statusbar.hide(); //You choice.  }, downloadCallback:function(filename,pd) 	{ 		location.href="download.php?filename="+filename; 	} }); 

Output:


11).Image Preview

To enable image preview, use the below configuration. Source:

 $("#previewupload").uploadFile({ url:"upload.php", fileName:"myfile", acceptFiles:"image/*", showPreview:true,  previewHeight: "100px",  previewWidth: "100px", }); 

Output:


12).Show already uploaded files

With the below configuration,plugin loads the previousily uploaded files. Source:

 $("#showoldupload").uploadFile({url: "upload.php", dragDrop: true, fileName: "myfile", returnType: "json", showDelete: true, showDownload:true, statusBarWidth:600, dragdropWidth:600, maxFileSize:200*1024, showPreview:true, previewHeight: "100px", previewWidth: "100px",  onLoad:function(obj)  {  	$.ajax({ 	 	cache: false, 		 url: "load.php", 	 	dataType: "json", 		 success: function(data)  		 { 			 for(var i=0;i<data.length;i++)  	 	{   			obj.createProgress(data[i]["name"],data[i]["path"],data[i]["size"]);  		} 	 } 		});  }, deleteCallback: function (data, pd) {  for (var i = 0; i < data.length; i++) {  $.post("delete.php", {op: "delete",name: data[i]},  function (resp,textStatus, jqXHR) {  //Show Message	  alert("File Deleted");  });  }  pd.statusbar.hide(); //You choice.  }, downloadCallback:function(filename,pd) 	{ 		location.href="download.php?filename="+filename; 	} }); 

Output:

hayageek.com

Здравствуйте!

Пытаюсь настроить загрузчик файлов «jQuery File Upload». Отображение на странице вроде настроил — выборка, старт загрузки и отмена функционируют.

Код формы:

<form id="fileupload" action="upload.php" method="POST" enctype="multipart/form-data"> 	<!-- Redirect browsers with JavaScript disabled to the origin page --> 	<noscript><input type="hidden" name="redirect" value="https://blueimp.github.io/jQuery-File-Upload/"></noscript> 	<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload --> 	<div class="row fileupload-buttonbar"> 		<div class="col-lg-7"> 			<!-- The fileinput-button span is used to style the file input field as button --> 			<span class="btn btn-success fileinput-button"> 				<i class="glyphicon glyphicon-plus"></i> 				<span>Add files...</span> 				<input id="fileupload" type="file" name="files[]" multiple data-url="/path/to/upload/handler.json" data-sequential-uploads="true" data-form-data='{"script": "true"}'> 			</span> 			<button type="submit" class="btn btn-primary start"> 				<i class="glyphicon glyphicon-upload"></i> 				<span>Start upload</span> 			</button> 			<button type="reset" class="btn btn-warning cancel"> 				<i class="glyphicon glyphicon-ban-circle"></i> 				<span>Cancel upload</span> 				</button> 			<button type="button" class="btn btn-danger delete"> 				<i class="glyphicon glyphicon-trash"></i> 				<span>Delete</span> 			</button> 			<input type="checkbox" class="toggle"> 			<!-- The global file processing state --> 			<span class="fileupload-process"></span> 		</div> 		<!-- The global progress state --> 		<div class="col-lg-5 fileupload-progress fade"> 			<!-- The global progress bar --> 			<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"> 				<div class="progress-bar progress-bar-success" style="width:0%;"></div> 			</div> 			<!-- The extended global progress state --> 			<div class="progress-extended">&nbsp;</div> 		</div> 	</div> 	<!-- The table listing the files available for upload/download --> 	<table role="presentation" class="table table-striped"><tbody class="files"></tbody></table> </form>  <!-- The blueimp Gallery widget --> <div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even"> 	<div class="slides"></div> 	<h3 class="title"></h3> 	<a class="prev">‹</a> 	<a class="next">›</a> 	<a class="close">×</a> 	<a class="play-pause"></a> 	<ol class="indicator"></ol> </div> <!-- The template to display files available for upload --> <script id="template-upload" type="text/x-tmpl"> 	{% for (var i=0, file; file=o.files[i]; i++) { %} 		<tr class="template-upload fade"> 			<td> 				<span class="preview"></span> 			</td> 			<td> 				<p class="name">{%=file.name%}</p> 				<strong class="error text-danger"></strong> 			</td> 			<td> 				<p class="size">Processing...</p> 				<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div> 			</td> 			<td> 				{% if (!i && !o.options.autoUpload) { %} 					<button class="btn btn-primary start" disabled> 						<i class="glyphicon glyphicon-upload"></i> 						<span>Start</span> 					</button> 				{% } %} 				{% if (!i) { %} 					<button class="btn btn-warning cancel"> 						<i class="glyphicon glyphicon-ban-circle"></i> 						<span>Cancel</span> 					</button> 				{% } %} 			</td> 		</tr> 	{% } %} </script> <!-- The template to display files available for download --> <script id="template-download" type="text/x-tmpl"> 	{% for (var i=0, file; file=o.files[i]; i++) { %} 		<tr class="template-download fade"> 			<td> 				<span class="preview"> 					{% if (file.thumbnailUrl) { %} 						<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a> 					{% } %} 				</span> 			</td> 			<td> 				<p class="name"> 					{% if (file.url) { %} 						<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a> 					{% } else { %} 						<span>{%=file.name%}</span> 					{% } %} 				</p> 				{% if (file.error) { %} 					<div><span class="label label-danger">Error</span> {%=file.error%}</div> 				{% } %} 			</td> 			<td> 				<span class="size">{%=o.formatFileSize(file.size)%}</span> 			</td> 			<td> 				{% if (file.deleteUrl) { %} 					<button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}> 						<i class="glyphicon glyphicon-trash"></i> 						<span>Delete</span> 					</button> 					<input type="checkbox" name="delete" value="1" class="toggle"> 				{% } else { %} 					<button class="btn btn-warning cancel"> 						<i class="glyphicon glyphicon-ban-circle"></i> 						<span>Cancel</span> 					</button> 				{% } %} 			</td> 		</tr> 	{% } %} </script>

Инициализируем форму:

<script type="text/javascript"> 	$('#fileupload').fileupload(); </script>

NYWL.png
NYWM.png

На скриншотах видно, что файлы добавляются, а по нажатию на кнопку «Start upload» запускается обработчик.

Код обработчика:

define ( 'ROOT_DIR', substr( dirname( __FILE__ ), 0, -21 ) );  error_reporting(E_ALL | E_STRICT);  require_once ROOT_DIR . '/UploadHandler.php';  echo "good"; // echo $_FILES['files'];  $upload_handler = new UploadHandler(array( 	'accept_file_types' => '/.(gif|jpe?g|png)$/i' ));

Что делать дальше не могу понять. На официальном сайте нет конкретных примеров. В репозитории на гитхабе в тестах тоже ничего не понял…

А не могу я понять конкретно содержание обработчика: как формировать необходимый json ответ и так далее…

Надеюсь на вашу помощь…

toster.ru

В этом уроке мы сделаем небольшую AJAX форму для загрузки файлов, которая позволит посетителям загружать файлы с помощью технологии drag/drop или при помощи обычного выбора файлов.

Мы будем использовать плагины jQuery File Upload и  jQuery Knob для отображения прогресса загрузки.

Т.к. форма будет иметь возможность загружать файлы двумя способами, она будет работать даже если drag/drop не поддерживается.

HTML

Как обычно, начнем с HTML5 разметки:

  <!DOCTYPE html>  <html>     <head>   <meta charset="utf-8"/>   <title>Mini Ajax File Upload Form</title>     <!-- Google web fonts -->   <link href="http://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700" rel='stylesheet' />     <!-- The main CSS file -->   <link href="assets/css/style.css" rel="stylesheet" />   </head>     <body>     <form id="upload" method="post" action="upload.php" enctype="multipart/form-data">   <div id="drop">   Drop Here     <a>Browse</a>   <input type="file" name="upl" multiple />   </div>     <ul>   <!-- загрузки будут показаны здесь -->   </ul>     </form>     <!-- JavaScript Includes -->   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>   <script src="assets/js/jquery.knob.js"></script>     <!-- jQuery File Upload Dependencies -->   <script src="assets/js/jquery.ui.widget.js"></script>   <script src="assets/js/jquery.iframe-transport.js"></script>   <script src="assets/js/jquery.fileupload.js"></script>     <!-- main JS file -->   <script src="assets/js/script.js"></script>     </body>  </html>  

В теге <head> нашего документа, подключаем шрифты Google Webfonts, а перед закрытием тега <body> — JavaScript библиотеки:  jQuery, jQuery Knob и jQuery File Upload.

Главный элемент страницы — форма #upload. Внутри нее элемент #drop (принимает файлы с использованием drag&drop)   и список, в котором будут отображаться загружаемые файлы. Разметка, которая будет генерироваться для загруженных файлов:

  <li class="working">   <input type="text" value="0" data-width="48" data-height="48" data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />   <p>Sunset.jpg <i>145 KB</i></p>   <span></span>  </li>  

Элемент input будет спрятан с помощью CSS. Он нужен для инициализации плагина jQuery Knob, который будет рисовать шкалу процесса загрузки файла.  Input имеет атрибуты data-*, которые используются для обновления шкалы. Позже, когда мы будет отслеживать прогресс загрузки, мы будем обновлять эти значения для перерисовки шкалы. span будет содержать зеленую галку или красный крест.

jQuery

У посетителя будет 2 способа загрузки файла:

  • Перетащить файл в окно браузера (в IE не работает).
  • Нажатием на кнопку browse. Будет имитировано нажатие на спрятанный input и показано системное окно выбора файлов. Обратите внимание, что input имеет параметр multiple параметр, что позволит выбирать много файлов за один раз.

Когда файлы будут выбраны, они помещаются в очередь для последующей автоматической загрузки:

  $(function(){     var ul = $('#upload ul');     $('#drop a').click(function(){   // имитация нажатия на поле выбора файла   $(this).parent().find('input').click();   });     // инициализация плагина jQuery File Upload   $('#upload').fileupload({     // этот элемент будет принимать перетаскиваемые на него файлы   dropZone: $('#drop'),     // Функция будет вызвана при помещении файла в очередь   add: function (e, data) {     var tpl = $('<li><input type="text" value="0" data-width="48" data-height="48"'+   ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');     // вывод имени и размера файла   tpl.find('p').text(data.files[0].name)   .append('<i>' + formatFileSize(data.files[0].size) + '</i>');     data.context = tpl.appendTo(ul);     // инициализация плагина jQuery Knob   tpl.find('input').knob();     // отслеживание нажатия на иконку отмены   tpl.find('span').click(function(){     if(tpl.hasClass('working')){   jqXHR.abort();   }     tpl.fadeOut(function(){   tpl.remove();   });     });     // Автоматически загружаем файл при добавлении в очередь   var jqXHR = data.submit();   },     progress: function(e, data){     // Вычисление процента загрузки   var progress = parseInt(data.loaded / data.total * 100, 10);     // обновляем шкалу   data.context.find('input').val(progress).change();     if(progress == 100){   data.context.removeClass('working');   }   },     fail:function(e, data){   // что-то пошло не так   data.context.addClass('error');   }     });     $(document).on('drop dragover', function (e) {   e.preventDefault();   });     // вспомогательная функция, которая форматирует размер файла   function formatFileSize(bytes) {   if (typeof bytes !== 'number') {   return '';   }     if (bytes >= 1000000000) {   return (bytes / 1000000000).toFixed(2) + ' GB';   }     if (bytes >= 1000000) {   return (bytes / 1000000).toFixed(2) + ' MB';   }     return (bytes / 1000).toFixed(2) + ' KB';   }    });  

В jQuery File Upload есть собственный интерфейс, но мы используем базовую версию плагина для создания собственного дизайна интерфейса. И чтобы наш интерфейс работал, мы передаем плагину несколько параметров / колбэков:

  • dropZone – этот параметр содержит jQuery селектор, который будет принимать перетаскиваемые файлы. Файлы, брошенные на него, будут добавлены в очередь загрузки.
  • add – функция вызывается при добавлении файла в очередь загрузки. Она будет генерировать разметку для файлов и вызвать метод data.submit().
  • progress – Эта функция будет вызываться каждые 100ms (можно изменить). Второй аргумент содержит размер файла и количество загруженных байт. Это позволяет отслеживать прогресс и обновлять шкалу.
  • fail – функция вызывается при возникновении ошибки.

easy-code.ru


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.