Added preview mode support to File upload widget

Widget also passes CSRF token
Switched to using a header instead of POST flag
This commit is contained in:
Samuel Georges 2015-06-25 06:14:02 +10:00
parent c87b075440
commit c813318729
29 changed files with 112 additions and 34 deletions

View File

@ -3,6 +3,7 @@
use Str;
use Lang;
use Input;
use Request;
use Response;
use Validator;
use System\Models\File;
@ -111,6 +112,12 @@ class FileUpload extends FormWidgetBase
*/
protected function prepareVars()
{
$this->previewMode = true;
if ($this->previewMode) {
$this->useCaption = false;
}
$this->vars['fileList'] = $fileList = $this->getFileList();
$this->vars['singleFile'] = $fileList->first();
$this->vars['displayMode'] = $this->getDisplayMode();
@ -335,7 +342,7 @@ class FileUpload extends FormWidgetBase
*/
protected function checkUploadPostback()
{
if (!($uniqueId = post('X_OCTOBER_FILEUPLOAD')) || $uniqueId != $this->getId()) {
if (!($uniqueId = Request::header('X-OCTOBER-FILEUPLOAD')) || $uniqueId != $this->getId()) {
return;
}

View File

@ -172,6 +172,11 @@
.field-fileupload.is-sortable .upload-object.dragged .uploader-toolbar {
display: none;
}
.field-fileupload.is-preview .upload-button,
.field-fileupload.is-preview .upload-remove-button,
.field-fileupload.is-preview .meta a.drag-handle {
display: none !important;
}
@media (max-width: 1024px) {
.field-fileupload .upload-object.is-success h4 a,
.field-fileupload .upload-object.is-success .meta .upload-remove-button,

View File

@ -41,6 +41,14 @@
this.options.isMulti = this.$el.hasClass('is-multi')
}
if (this.options.isPreview === null) {
this.options.isPreview = this.$el.hasClass('is-preview')
}
if (this.options.isSortable === null) {
this.options.isSortable = this.$el.hasClass('is-sortable')
}
this.$el.one('dispose-control', this.proxy(this.dispose))
this.$uploadButton = $('.upload-button', this.$el)
this.$filesContainer = $('.upload-files-container', this.$el)
@ -48,12 +56,19 @@
this.$el.on('click', '.upload-object.is-success', this.proxy(this.onClickSuccessObject))
this.$el.on('click', '.upload-object.is-error', this.proxy(this.onClickErrorObject))
// Stop here for preview mode
if (this.options.isPreview)
return
this.$el.on('click', '.upload-remove-button', this.proxy(this.onRemoveObject))
this.bindUploader()
if (this.$el.hasClass('is-sortable')) {
if (this.options.isSortable) {
this.bindSortable()
}
}
FileUpload.prototype.dispose = function() {
@ -87,7 +102,8 @@
paramName: this.options.paramName,
clickable: this.$uploadButton.get(0),
previewsContainer: this.$filesContainer.get(0),
maxFiles: !this.options.isMulti ? 1 : null
maxFiles: !this.options.isMulti ? 1 : null,
headers: {}
}
if (this.options.fileTypes) {
@ -99,7 +115,15 @@
}
if (this.options.uniqueId) {
this.options.extraData = $.extend({}, this.options.extraData, { X_OCTOBER_FILEUPLOAD: this.options.uniqueId })
this.uploaderOptions.headers['X-OCTOBER-FILEUPLOAD'] = this.options.uniqueId
}
/*
* Add CSRF token to headers
*/
var token = $('meta[name="csrf-token"]').attr('content')
if (token) {
this.uploaderOptions.headers['X-CSRF-TOKEN'] = token
}
this.dropzone = new Dropzone(this.$el.get(0), this.uploaderOptions)
@ -300,7 +324,9 @@
fileTypes: null,
template: null,
errorTemplate: null,
isMulti: null
isMulti: null,
isPreview: null,
isSortable: null
}
// FILEUPLOAD PLUGIN DEFINITION

View File

@ -327,6 +327,18 @@
}
}
}
//
// Preview mode
//
&.is-preview {
.upload-button,
.upload-remove-button,
.meta a.drag-handle {
display: none !important;
}
}
}
//

View File

@ -1,6 +1,6 @@
<div
id="<?= $this->getId() ?>"
class="field-fileupload style-file-multi is-sortable is-multi <?= count($fileList) ? 'is-populated' : '' ?>"
class="field-fileupload style-file-multi is-sortable is-multi <?= count($fileList) ? 'is-populated' : '' ?> <?= $this->previewMode ? 'is-preview' : '' ?>"
data-control="fileupload"
data-template="#<?= $this->getId('template') ?>"
data-error-template="#<?= $this->getId('errorTemplate') ?>"

View File

@ -1,6 +1,6 @@
<div
id="<?= $this->getId() ?>"
class="field-fileupload style-file-single <?= $singleFile ? 'is-populated' : '' ?>"
class="field-fileupload style-file-single <?= $singleFile ? 'is-populated' : '' ?> <?= $this->previewMode ? 'is-preview' : '' ?>"
data-control="fileupload"
data-template="#<?= $this->getId('template') ?>"
data-error-template="#<?= $this->getId('errorTemplate') ?>"

View File

@ -1,31 +1,39 @@
<?php switch ($displayMode):
<?php if ($this->previewMode && !$fileList->count()): ?>
case 'image-single': ?>
<?= $this->makePartial('image_single') ?>
<?php break ?>
<span class="form-control"><?= e(trans('backend::lang.form.preview_no_files_message')) ?></span>
<?php case 'image-multi': ?>
<?= $this->makePartial('image_multi') ?>
<?php break ?>
<?php else: ?>
<?php case 'file-single': ?>
<?= $this->makePartial('file_single') ?>
<?php break ?>
<?php switch ($displayMode):
<?php case 'file-multi': ?>
<?= $this->makePartial('file_multi') ?>
<?php break ?>
case 'image-single': ?>
<?= $this->makePartial('image_single') ?>
<?php break ?>
<?php endswitch ?>
<?php case 'image-multi': ?>
<?= $this->makePartial('image_multi') ?>
<?php break ?>
<!-- Error template -->
<script type="text/template" id="<?= $this->getId('errorTemplate') ?>">
<div class="popover-head">
<h3>Upload error</h3>
<p>{{errorMsg}}</p>
<button type="button" class="close" data-dismiss="popover" aria-hidden="true">&times;</button>
</div>
<div class="popover-body">
<button class="btn btn-danger" data-remove-file>Remove file</button>
</div>
</script>
<?php case 'file-single': ?>
<?= $this->makePartial('file_single') ?>
<?php break ?>
<?php case 'file-multi': ?>
<?= $this->makePartial('file_multi') ?>
<?php break ?>
<?php endswitch ?>
<!-- Error template -->
<script type="text/template" id="<?= $this->getId('errorTemplate') ?>">
<div class="popover-head">
<h3>Upload error</h3>
<p>{{errorMsg}}</p>
<button type="button" class="close" data-dismiss="popover" aria-hidden="true">&times;</button>
</div>
<div class="popover-body">
<button class="btn btn-danger" data-remove-file>Remove file</button>
</div>
</script>
<?php endif ?>

View File

@ -1,6 +1,6 @@
<div
id="<?= $this->getId() ?>"
class="field-fileupload style-image-multi is-sortable is-multi <?= count($fileList) ? 'is-populated' : '' ?>"
class="field-fileupload style-image-multi is-sortable is-multi <?= count($fileList) ? 'is-populated' : '' ?> <?= $this->previewMode ? 'is-preview' : '' ?>"
data-control="fileupload"
data-template="#<?= $this->getId('template') ?>"
data-error-template="#<?= $this->getId('errorTemplate') ?>"

View File

@ -1,6 +1,6 @@
<div
id="<?= $this->getId() ?>"
class="field-fileupload style-image-single <?= $singleFile ? 'is-populated' : '' ?>"
class="field-fileupload style-image-single <?= $singleFile ? 'is-populated' : '' ?> <?= $this->previewMode ? 'is-preview' : '' ?>"
data-control="fileupload"
data-template="#<?= $this->getId('template') ?>"
data-error-template="#<?= $this->getId('errorTemplate') ?>"

View File

@ -156,6 +156,7 @@ return [
'or' => 'or',
'confirm_tab_close' => 'Wollen Sie den Tab wirklich schließen? Ungespeicherte Änderungen gehen verloren.',
'behavior_not_ready' => 'Formularverhalten kann nicht initialisiert werden, überprüfen Sie den Aufruf von makeLists() in Ihrem Controller.',
'preview_no_files_message' => 'Keine Dateien wurden hochgeladen',
'select' => 'Auswählen',
'select_all' => 'Alle',
'select_none' => 'Keine',

View File

@ -185,6 +185,7 @@ return [
'or' => 'or',
'confirm_tab_close' => 'Do you really want to close the tab? Unsaved changes will be lost.',
'behavior_not_ready' => 'Form behavior has not been initialized, check that you have called initForm() in your controller.',
'preview_no_files_message' => 'There are no files uploaded.',
'select' => 'Select',
'select_all' => 'all',
'select_none' => 'none',

View File

@ -159,6 +159,7 @@ return [
'or' => 'o',
'confirm_tab_close' => '¿Realmente desea cerrar la cuenta? Se perderán los cambios no guardados.',
'behavior_not_ready' => 'Favor compruebe que ha llamado a la funcion initForm() en el controlador.',
'preview_no_files_message' => 'Los archivos no fueron cargados',
'select' => 'Seleccionar',
'select_all' => 'Todo',
'select_none' => 'Nada',

View File

@ -161,6 +161,7 @@ return [
'or' => 'o',
'confirm_tab_close' => '¿Realmente desea cerrar la pestaña? Se perderán los cambios no guardados.',
'behavior_not_ready' => 'El comportamiento del formulario no se ha inicializado, compruebe que ha llamado initForm() en el controlador.',
'preview_no_files_message' => 'Los archivos no se han subido',
'select' => 'Seleccionar',
'select_all' => 'todos',
'select_none' => 'ninguno',

View File

@ -167,6 +167,7 @@ return [
'or' => 'یا',
'confirm_tab_close' => 'در صورت بستن این پنجره موارد ذخیره نشده از بین خواهند رفت. آیا از حذف شدن این پنجره اطمینان دارید؟',
'behavior_not_ready' => 'فرم مور نظر مقدار دهی اولیه نشده است ، بررسی کنید که متد initForm() در کنترلر فرتخوانی شده باشد.',
'preview_no_files_message' => 'فایل ها ارسال نشدند',
'select' => 'انتخاب',
'select_all' => 'همه',
'select_none' => 'هیچ',

View File

@ -180,6 +180,7 @@ return [
'or' => 'ou',
'confirm_tab_close' => 'Confirmer la fermeture de cet onglet ? Les modifications réalisées seront perdues.',
'behavior_not_ready' => 'Le formulaire na pas encore été initialisé, vérifier que la méthode dappel de initForm() a été soumise au contrôleur.',
'preview_no_files_message' => 'Les fichiers ne sont pas envoyés.',
'select' => 'Sélectionner',
'select_all' => 'tout',
'select_none' => 'aucun',

View File

@ -180,6 +180,7 @@ return [
'or' => 'vagy',
'confirm_tab_close' => 'Valóban be akarja zárni a fület? El fognak veszni a nem mentett módosítások.',
'behavior_not_ready' => 'Nem történt meg az űrlapviselkedés inicializálása, ellenőrizze, hogy meghívta-e az initForm() függvényt a vezérlőben.',
'preview_no_files_message' => 'A fájlok nincsenek feltöltve',
'select' => 'Válasszon',
'select_all' => 'mind',
'select_none' => 'egyik sem',

View File

@ -180,6 +180,7 @@ return [
'or' => 'atau',
'confirm_tab_close' => 'Anda yakin akan menutup tab? Perubahan belum tersimpan akan hilang.',
'behavior_not_ready' => 'Behavior borang belum diinisialisasi, periksa apakah Anda telah memanggil initForm() pada controller Anda.',
'preview_no_files_message' => 'Berkas tidak terunggah',
'select' => 'Pilih',
'select_all' => 'semua',
'select_none' => 'tiada',

View File

@ -145,6 +145,7 @@ return [
'or' => 'o',
'confirm_tab_close' => 'Vuoi davvero chiudere il tab? Le modifiche non salvate andranno perse.',
'behavior_not_ready' => 'Il form non è stato inizializzato, verifica di aver chiamato il metodo initForm() nel controller.',
'preview_no_files_message' => 'I file non sono stati caricati',
'select' => 'Seleziona',
'select_all' => 'tutti',
'select_none' => 'nessuno',

View File

@ -176,6 +176,7 @@ return [
'or' => 'または',
'confirm_tab_close' => '本当にタブを閉じますか? 保存されていない変更は消えてしまいます。',
'behavior_not_ready' => 'フォームビヘイビアーは初期化されていません。コントローラーでinitForm()を呼び出しているか確認してください。',
'preview_no_files_message' => 'ファイルはアップロードされません。',
'select' => '選択',
'select_all' => 'すべて',
'select_none' => 'なし',

View File

@ -180,6 +180,7 @@ return [
'or' => 'vai',
'confirm_tab_close' => 'Vai tiešām vēlaties aizvērt šo cilni? Nesaglabātās izmaiņas būs zudušas.',
'behavior_not_ready' => 'Forma nav tikusi inicializēta, pārbaudiet vai izsaucāt initForm() savā kontrolierī.',
'preview_no_files_message' => 'Faili nav augšupielādēti',
'select' => 'Izvēlēties',
'select_all' => 'visus',
'select_none' => 'nevienu',

View File

@ -181,6 +181,7 @@ return [
'or' => 'eller',
'confirm_tab_close' => 'Vil du virkelig lukke fanen? Endringer som ikke er lagret vil gå tapt.',
'behavior_not_ready' => 'Skjemaegenskap har ikke blitt initialisert, sjekk at du har kalt initForm() i kontrolleren.',
'preview_no_files_message' => 'Filer er ikke opplastet',
'select' => 'Velg',
'select_all' => 'alle',
'select_none' => 'ingen',

View File

@ -158,6 +158,7 @@ return [
'or' => 'of',
'confirm_tab_close' => 'Weet je zeker dat je dit tabblad wilt sluiten? Niet opgeslagen wijzigingen gaan verloren.',
'behavior_not_ready' => 'Gedrag (behavior) van het formulier is niet geladen. Controleer of initForm() in de controller is aangeroepen.',
'preview_no_files_message' => 'Bestanden zijn niet geüploadet',
'select' => 'Selecteer',
'select_all' => 'alles',
'select_none' => 'niets',

View File

@ -176,6 +176,7 @@ return [
'or' => 'lub',
'confirm_tab_close' => 'Czy naprawdę chcesz zamknąć tą kartę? Wszystkie niezapisane zmiany zostaną utracone.',
'behavior_not_ready' => 'Zachowanie formularza nie zostało zainicjowane, sprawdź czy wywołałeś initForm() w swoim kontrolerze.',
'preview_no_files_message' => 'Pliki nie są wysyłane',
'select' => 'Zaznacz',
'select_all' => 'wszystkie',
'select_none' => 'żadne',

View File

@ -180,6 +180,7 @@ return [
'or' => 'ou',
'confirm_tab_close' => 'Tem certeza que deseja fechar essa aba? As alterações que não foram salvas serão perdidas',
'behavior_not_ready' => 'O formulário não foi inicializado. Confira se você chamou initForm() no controller.',
'preview_no_files_message' => 'Os arquivos não foram carregados',
'select' => 'Selecionar',
'select_all' => 'todos',
'select_none' => 'nenhum',

View File

@ -147,6 +147,7 @@ return [
'or' => 'sau',
'confirm_tab_close' => 'Sunteti sigur(a) ca doriti sa inchideti acest tab? Modificarile nesalvate vor fi pierdute.',
'behavior_not_ready' => 'Setarile initiale ale formularului nu au fost definite, verificati existenta functiei initForm() in controller.',
'preview_no_files_message' => 'Fisierele nu au fost incarcate',
'select' => 'Selectare',
'select_all' => 'toate',
'select_none' => 'niciunul',

View File

@ -181,6 +181,7 @@ return [
'or' => 'или',
'confirm_tab_close' => 'Закрыть вкладку? Несохраненные изменения будут потеряны.',
'behavior_not_ready' => 'Поведение формы не было инициализировано, проверьте вызов initForm() в вашем контроллере.',
'preview_no_files_message' => 'Файлы не загружены',
'select' => 'Выбрать',
'select_all' => 'все',
'select_none' => 'ничего',

View File

@ -180,6 +180,7 @@ return [
'or' => 'eller',
'confirm_tab_close' => 'Vill du verkligen stänga fliken? Ej sparade ändringar kommer gå förlorade',
'behavior_not_ready' => 'Formuläregenskap har ej blivit initierad, kontrollera att du anropat initForm() i din controller',
'preview_no_files_message' => 'Filen är inte uppladdad',
'select' => 'Välj',
'select_all' => 'alla',
'select_none' => 'ingen',

View File

@ -176,6 +176,7 @@ return [
'or' => 'veya',
'confirm_tab_close' => 'Bu sekmeyi kapatmak istediğinize emin misiniz? Kaydedilmemiş değişiklikleri kaybedeceksiniz.',
'behavior_not_ready' => 'Form oluşturulamadı, controller da initForm() metodunu kontrol edin.',
'preview_no_files_message' => 'Dosyalar yüklenmedi',
'select' => 'Seç',
'select_all' => 'tümü',
'select_none' => 'hiçbiri',

View File

@ -180,6 +180,7 @@ return [
'or' => '或',
'confirm_tab_close' => '你真的想要关闭这个标签吗? 未保存的改变会丢失.',
'behavior_not_ready' => '表单还没初始化, 确保你调用了controller中的 initForm().',
'preview_no_files_message' => '文件没有上传',
'select' => '选择',
'select_all' => 'all',
'select_none' => 'none',