// Uploader helper part 3

This commit is contained in:
Jerome Nadaud
2013-11-07 16:42:00 +01:00
parent de8bd97831
commit 18718792be
7 changed files with 163 additions and 173 deletions
@@ -43,6 +43,18 @@
{/if}
</div>
</div>
{if isset($max_files) && $files|count >= $max_files}
<div class="row">
<div class="alert alert-warning">{l s='You have reached the limit (%s) of files to upload, please remove files to continue uploading' sprintf=$max_files}</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
{if isset($files) && $files}
$('#{$id}-images-thumbnails').parent().show();
{/if}
});
</script>
{else}
<div class="form-group">
<div class="col-lg-12">
<input id="{$id}" type="file" name="{$name}[]"{if isset($url)} data-url="{$url}"{/if}{if isset($multiple) && $multiple} multiple="multiple"{/if} class="hide" />
@@ -55,167 +67,138 @@
</div>
</div>
<div class="row" style="display:none">
<div class="alert alert-info" id="{$id}-files-list">
<strong>{l s='Files:'}</strong>
<br />
</div>
<div class="alert alert-info" id="{$id}-files-list"></div>
</div>
<div class="row" style="display:none">
<div class="alert alert-success" id="{$id}-success"></div>
</div>
<div class="row" style="display:none">
<div class="alert alert-danger" id="{$id}-errors"></div>
</div>
<script type="text/javascript">
function humanizeSize(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';
}
$( document ).ready(function() {
{if isset($multiple) && isset($max_files)}
var {$id}_max_files = {$max_files};
var {$id}_max_files = {$max_files - $files|count};
{/if}
{if isset($files) && $files}
$('#{$id}-images-thumbnails').parent().show();
{/if}
var {$id}_total_files = 0;
var {$id}_upload_button = Ladda.create( document.querySelector('#{$id}-upload-button' ));
var {$id}_total_files = 0;
var data = $('#{$id}').fileupload({
$('#{$id}').fileupload({
dataType: 'json',
autoUpload: false,
singleFileUploads: false,
add: function(e, data) {
if (typeof {$id}_max_files !== 'undefined') {
if ({$id}_total_files >= {$id}_max_files || data.originalFiles.length > {$id}_max_files) {
e.preventDefault();
alert('{l s='You can upload a maximum of %s files'|sprintf:$max_files}');
return;
}
}
{$id}_total_files++;
$('#{$id}-upload-button').show().on('click', function () {
data.submit();
});
},
start: function () {
singleFileUploads: true,
maxFileSize: {$post_max_size},
start: function (e) {
{$id}_upload_button.start();
$('#{$id}-upload-button').unbind('click'); //Important as we bind it for every elements in add function
},
fail: function (e, data) {
$('#{$id}-errors').html(data.errorThrown.message).parent().show();
},
done: function (e, data) {
if (typeof data.result.{$name} !== 'undefined') {
for (var i=0; i<data.result.{$name}.length; i++) {
if (typeof data.result.{$name}[i].image !== 'undefined') {
var template = '<div class="img-thumbnail text-center">';
template += '<p>'+data.result.{$name}[i].image+'</p>';
if (typeof data.result.{$name}[i].delete_url !== 'undefined') {
template += '<p><a class="btn btn-default" href="'+data.result.{$name}[i].delete_url+'"><i class="icon-trash"></i> {l s='Delete'}</a></p>';
}
if (data.result) {
if (typeof data.result.{$name} !== 'undefined') {
for (var i=0; i<data.result.{$name}.length; i++) {
if (data.result.{$name}[i] !== null) {
if (typeof data.result.{$name}[i].image !== 'undefined') {
var template = '<div class="img-thumbnail text-center">';
template += '<p>'+data.result.{$name}[i].image+'</p>';
if (typeof data.result.{$name}[i].delete_url !== 'undefined') {
template += '<p><a class="btn btn-default" href="'+data.result.{$name}[i].delete_url+'"><i class="icon-trash"></i> {l s='Delete'}</a></p>';
}
template += '</div>';
$('#{$id}-images-thumbnails').html($('#{$id}-images-thumbnails').html()+template);
$('#{$id}-images-thumbnails').parent().show();
template += '</div>';
$('#{$id}-images-thumbnails').html($('#{$id}-images-thumbnails').html()+template);
$('#{$id}-images-thumbnails').parent().show();
}
}
}
}
$(data.context).find('button').remove();
$(data.context).appendTo($('#{$id}-success'));
$('#{$id}-success').parent().show();
}
},
always: function (e, data) {
{$id}_upload_button.stop();
}
});
}).on('fileuploadalways', function (e, data) {
{$id}_total_files--;
$('#{$id}-add-button').on('click', function() {
$('#{$id}').trigger('click');
});
});
/**/
/*
var total_files = 0;
var total_uploaded_files = 0;
{if isset($multiple) && isset($max_files)}
var {$id}_max_files = {$max_files};
{/if}
$('#{$id}').fileupload(
{
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: false,
done: function (e, data) {
$.each(data.result, function (index, file) {
if (file[0].error)
$('#{$id}-errors').append(file[0].error+'<br/>').parent().show();
else
total_uploaded_files ++;
});
if (total_uploaded_files == data.originalFiles.length)
$('#{$id}-upload-button').css('background-color', 'green').children('.icon-cloud-upload').removeClass('icon-cloud-upload').addClass('icon-check');
},
progressall: function (e, data) {
upload_button.setProgress(data.loaded / data.total);
},
add: function (e, data) {
console.log(data.originalFiles.length);
if (typeof {$id}_max_files !== 'undefined')
{
if (data.originalFiles.length > {$id}_max_files) {
if ({$id}_total_files == 0)
{
{$id}_upload_button.stop();
$('#{$id}-upload-button').unbind('click');
$('#{$id}-files-list').parent().hide();
}
}).on('fileuploadadd', function(e, data) {
if (typeof {$id}_max_files !== 'undefined') {
if ({$id}_total_files >= {$id}_max_files) {
e.preventDefault();
alert('{l s='You can upload a maximum of %s files'|sprintf:$max_files}');
return;
}
}
data.context = $('#{$id}-files-list');
data.context.parent().show();
data.context = $('<div/>').addClass('row').appendTo($('#{$id}-files-list'));
var file_name = $('<span/>').append('<strong>'+data.files[0].name+'</strong> ('+humanizeSize(data.files[0].size)+')').appendTo(data.context);
$.each(data.files, function (index, file) {
var node = '<div class="row"><span>'+file.name+'</span><button class="btn btn-default pull-right" type="button"><i class="icon-trash"></i> Remove from list</button></div>';
data.context.append(node);
});
var button = $('<button/>').addClass('btn btn-default pull-right').prop('type', 'button').html('<i class="icon-trash"></i> {l s='Remove file'}').appendTo(data.context).on('click', function() {
{$id}_total_files--;
data.files = null;
var total_elements = $(this).parent().siblings('div.row').length;
$(this).parent().remove();
$('#{$id}-upload-button').show().on('click', function () {
total_files = data.originalFiles.length;
data.submit();
});
},
fail: function (e, data) {
$('#{$id}-errors').html(data.errorThrown.message).parent().show();
},
always: function (e, data) {
total_files--;
if (total_elements == 0) {
$('#{$id}-files-list').html('').parent().hide();
}
});
if (total_files == 0)
upload_button.stop();
}
});*/
$('#{$id}-files-list').parent().show();
$('#{$id}-upload-button').show().bind('click', function () {
if (data.files != null)
data.submit();
});
</script>
{$id}_total_files++;
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index, file = data.files[index];
if (file.error) {
$('#{$id}-errors').append('<div class="row"><strong>'+file.name+'</strong> ('+humanizeSize(file.size)+') : '+file.error+'</div>').parent().show();
$(data.context).find('button').trigger('click');
}
});
$('#{$id}-add-button').on('click', function() {
$('#{$id}-success').html('').parent().hide();
$('#{$id}-errors').html('').parent().hide();
$('#{$id}-files-list').html('').parent().hide();
{$id}_total_files = 0;
$('#{$id}').trigger('click');
});
});
</script>
{/if}
@@ -50,6 +50,11 @@
</div>
</div>
{/if}
{if isset($max_files) && $files|count >= $max_files}
<div class="row">
<div class="alert alert-warning">{l s='You have reached the limit (%s) of files to upload, please remove files to continue uploading' sprintf=$max_files}</div>
</div>
{else}
<div class="form-group">
<div class="col-lg-12">
<input id="{$id}" type="file" name="{$name}"{if isset($multiple) && $multiple} multiple="multiple"{/if} class="hide" />
@@ -72,10 +77,9 @@
</div>
</div>
</div>
<script type="text/javascript">
{if isset($multiple) && isset($max_files)}
var {$id}_max_files = {$max_files};
var {$id}_max_files = {$max_files - $files|count};
{/if}
$(document).ready(function(){
@@ -116,4 +120,5 @@
});
}
});
</script>
</script>
{/if}
+24 -21
View File
@@ -48,9 +48,6 @@ class UploaderCore
public function getAcceptTypes()
{
if (!isset($this->_accept_types))
$this->setAcceptTypes('/.+$/i');
return $this->_accept_types;
}
@@ -101,6 +98,21 @@ class UploaderCore
return $this;
}
public function getPostMaxSizeBytes() {
$post_max_size = ini_get('post_max_size');
$bytes = trim($post_max_size);
$last = strtolower($post_max_size[strlen($post_max_size) - 1]);
switch ($last)
{
case 'g': $bytes *= 1024;
case 'm': $bytes *= 1024;
case 'k': $bytes *= 1024;
}
return $bytes;
}
public function getSavePath()
{
if (!isset($this->_save_path))
@@ -134,8 +146,11 @@ class UploaderCore
$this->files[] = $this->upload($tmp[$index]);
}
}
else
elseif ($upload)
{
$this->files[] = $this->upload($upload);
}
return $this->files;
}
@@ -173,7 +188,7 @@ class UploaderCore
protected function validate($file)
{
$post_max_size = $this->_getPostMaxSizeBytes();
$post_max_size = $this->getPostMaxSizeBytes();
if ($post_max_size && ($this->_getServerVars('CONTENT_LENGTH') > $post_max_size))
{
@@ -181,7 +196,10 @@ class UploaderCore
return false;
}
if (!preg_match($this->getAcceptTypes(), $file['name']))
$types = $this->getAcceptTypes();
//TODO check mime type.
if (isset($types) && !in_array(pathinfo($file['name'], PATHINFO_EXTENSION), $types))
{
$file['error'] = Tools::displayError('Filetype not allowed');
return false;
@@ -203,21 +221,6 @@ class UploaderCore
return filesize($file_path);
}
protected function _getPostMaxSizeBytes() {
$post_max_size = ini_get('post_max_size');
$bytes = trim($post_max_size);
$last = strtolower($post_max_size[strlen($post_max_size) - 1]);
switch ($last)
{
case 'g': $bytes *= 1024;
case 'm': $bytes *= 1024;
case 'k': $bytes *= 1024;
}
return $bytes;
}
protected function _getServerVars($var)
{
return (isset($_SERVER[$var]) ? $_SERVER[$var] : '');
+1 -1
View File
@@ -118,6 +118,7 @@ class HelperFormCore extends Helper
$uploader->setUrl(isset($params['url'])?$params['url']:null);
$uploader->setMultiple(isset($params['multiple'])?$params['multiple']:false);
$uploader->setUseAjax(isset($params['ajax'])?$params['ajax']:false);
$uploader->setMaxFiles(isset($params['max_files'])?$params['max_files']:null);
if (isset($params['files']) && $params['files'])
$uploader->setFiles($params['files']);
@@ -139,7 +140,6 @@ class HelperFormCore extends Helper
'download_url' => isset($params['file'])?$params['file']:null
)));
$uploader->setThumb(isset($params['thumb'])?$params['thumb']:null);
$uploader->setTitle(isset($params['title'])?$params['title']:null);
+8 -15
View File
@@ -26,35 +26,25 @@
class HelperImageUploaderCore extends HelperUploader
{
private $_temporary_path;
public function getMaxSize()
{
return (int)Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE');
}
public function setTemporaryPath($value)
public function getSavePath()
{
$this->_temporary_path = $value;
}
public function getTemporaryPath()
{
if (!isset($this->_temporary_path))
$this->_temporary_path = _PS_TMP_IMG_DIR_;
return $this->_normalizeDirectory($this->_temporary_path);
return $this->_normalizeDirectory(_PS_TMP_IMG_DIR_);
}
public function getFilePath($file_name = null)
{
//Force file path
return tempnam($this->getTemporaryPath(), $this->getUniqueFileName());
return tempnam($this->getSavePath(), $this->getUniqueFileName());
}
protected function validate($file)
{
$post_max_size = $this->_getPostMaxSizeBytes();
$post_max_size = $this->getPostMaxSizeBytes();
if ($post_max_size && ($this->_getServerVars('CONTENT_LENGTH') > $post_max_size))
{
@@ -62,7 +52,10 @@ class HelperImageUploaderCore extends HelperUploader
return false;
}
if (!preg_match($this->getAcceptTypes(), $file['name']))
$types = $this->getAcceptTypes();
//TODO check mime type.
if (isset($types) && !in_array(pathinfo($file['name'], PATHINFO_EXTENSION), $types))
{
$file['error'] = Tools::displayError('Filetype not allowed');
return false;
+1
View File
@@ -104,6 +104,7 @@ class HelperOptionsCore extends Helper
$uploader->setUrl(isset($field['url'])?$field['url']:null);
$uploader->setMultiple(isset($field['multiple'])?$field['multiple']:false);
$uploader->setUseAjax(isset($field['ajax'])?$field['ajax']:false);
$uploader->setMaxFiles(isset($field['max_files'])?$field['max_files']:null);
if (isset($field['files']) && $field['files'])
$uploader->setFiles($field['files']);
+13 -8
View File
@@ -243,22 +243,28 @@ class HelperUploaderCore extends Uploader
.'/themes/'.$bo_theme.'/js/vendor/jquery.ui.widget.js"></script>';
$html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/jquery.iframe-transport.js"></script>';
$html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.$admin_webpath
$html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/jquery.fileupload.js"></script>';
$html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/jquery.fileupload-process.js"></script>';
$html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/jquery.fileupload-validate.js"></script>';
$html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.'/js/vendor/spin.js"></script>';
$html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.'/js/vendor/ladda.js"></script>';
}
else
{
$html = '';
$this->getContext()->controller->addJs(__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/vendor/jquery.ui.widget.js');
//$context->controller->addJs('http://blueimp.github.io/JavaScript-Load-Image/js/load-image.min.js');
$this->getContext()->controller->addJs(__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/jquery.iframe-transport.js');
$this->getContext()->controller->addJs(__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/jquery.fileupload.js');
/*$context->controller->addJs(__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/jquery.fileupload-image.js');*/
$this->getContext()->controller->addJs(__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/jquery.fileupload-process.js');
$this->getContext()->controller->addJs(__PS_BASE_URI__.$admin_webpath
.'/themes/'.$bo_theme.'/js/jquery.fileupload-validate.js');
$this->getContext()->controller->addJs(__PS_BASE_URI__.'/js/vendor/spin.js');
$this->getContext()->controller->addJs(__PS_BASE_URI__.'/js/vendor/ladda.js');
}
@@ -270,8 +276,6 @@ class HelperUploaderCore extends Uploader
$this->getTemplateFile($this->getTemplate()), $this->getContext()->smarty
);
$max_files = $this->getMaxFiles();
$template->assign(array(
'id' => $this->getId(),
'name' => $this->getName(),
@@ -280,7 +284,8 @@ class HelperUploaderCore extends Uploader
'files' => $this->getFiles(),
'thumb' => $this->getThumb(),
'title' => $this->getTitle(),
'max_files' => (isset($max_files) && $max_files > 0) ? ($max_files-count($this->getFiles())) : $max_files
'max_files' => $this->getMaxFiles(),
'post_max_size' => $this->getPostMaxSizeBytes()
));
$html .= $template->fetch();