Skip to content

Instantly share code, notes, and snippets.

@janmarek
Created April 23, 2010 15:59
Show Gist options
  • Save janmarek/376724 to your computer and use it in GitHub Desktop.
Save janmarek/376724 to your computer and use it in GitHub Desktop.
HTML 5 multiple file upload
<?php
/**
* Nette Framework
*
* @copyright Copyright (c) 2004, 2010 David Grudl
* @license http://nettephp.com/license Nette license
* @link http://nettephp.com
* @category Nette
* @package Nette\Forms
*/
namespace Nette\Forms;
use Nette;
use Nette\Web\HttpUploadedFile;
/**
* HTML 5 multiple file upload
*
* @copyright Copyright (c) 2010 Jan Marek
* @package Nette\Forms
*/
class MultipleFileUpload extends FileUpload
{
/**
* @param string label
*/
public function __construct($label = NULL)
{
parent::__construct($label);
$this->control->multiple = "true";
}
/**
* Generates control's HTML element.
* @return Nette\Web\Html
*/
public function getControl() {
$control = parent::getControl();
$control->name = $this->getHtmlName() . "[]";
$control->class[] = "multiple-file-upload";
return $control;
}
/**
* Sets control's value.
* @param array|Nette\Web\HttpUploadedFile
* @return FileUpload provides a fluent interface
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Filled validator: has been any file uploaded?
* @param IFormControl
* @return bool
*/
public static function validateFilled(IFormControl $control)
{
foreach ($control->getValue() as $file) {
if (!($file instanceof HttpUploadedFile && $file->isOK())) {
return FALSE;
}
}
return TRUE;
}
/**
* FileSize validator: is file size in limit?
* @param FileUpload
* @param int file size limit
* @return bool
*/
public static function validateFileSize(FileUpload $control, $limit)
{
foreach ($control->getValue() as $file) {
if (!($file instanceof HttpUploadedFile && $file->getSize() <= $limit)) {
return FALSE;
}
}
return TRUE;
}
/**
* MimeType validator: has file specified mime type?
* @param FileUpload
* @param array|string mime type
* @return bool
*/
public static function validateMimeType(FileUpload $control, $mimeType)
{
foreach ($control->getValue() as $file) {
if (!self::validateMimeTypeSingle($file, $mimeType)) {
return FALSE;
}
}
return TRUE;
}
/**
* MimeType validator helper
* @param mixed
* @param array|string mime type
* @return bool
*/
private static function validateMimeTypeSingle($file, $mimeType)
{
if ($file instanceof HttpUploadedFile) {
$type = $file->getContentType();
$type = strtolower(preg_replace('#\s*;.*$#', '', $type));
if (!$type) {
return FALSE; // cannot verify :-(
}
$mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
if (in_array($type, $mimeTypes, TRUE)) {
return TRUE;
}
if (in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, TRUE)) {
return TRUE;
}
}
return FALSE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment