├── src ├── views │ ├── gallery.php │ ├── uploadButton.php │ ├── upload.php │ ├── download.php │ └── form.php ├── messages │ ├── tr-TR │ │ └── fileupload.php │ ├── zh-TW │ │ └── fileupload.php │ ├── en │ │ └── fileupload.php │ ├── vi-VN │ │ └── fileupload.php │ ├── zh-CN │ │ └── fileupload.php │ ├── sk │ │ └── fileupload.php │ ├── pt-PT │ │ └── fileupload.php │ ├── he │ │ └── fileupload.php │ ├── fa-IR │ │ └── fileupload.php │ ├── it │ │ └── fileupload.php │ ├── fr │ │ └── fileupload.php │ ├── pl │ │ └── fileupload.php │ ├── de │ │ └── fileupload.php │ ├── nl │ │ └── fileupload.php │ ├── bg │ │ └── fileupload.php │ ├── ru │ │ └── fileupload.php │ ├── lv │ │ └── fileupload.php │ ├── es-MX │ │ └── fileupload.php │ ├── es │ │ └── fileupload.php │ ├── pt-BR │ │ └── fileupload.php │ ├── el │ │ └── fileupload.php │ └── uz-UZ │ │ └── fileupload.php ├── BlueimpTmplAsset.php ├── BlueimpLoadImageAsset.php ├── BlueimpCanvasToBlobAsset.php ├── FileUploadAsset.php ├── FileUploadPlusAsset.php ├── FileUploadUIAsset.php ├── BaseUpload.php ├── FileUpload.php ├── actions │ ├── FileListAction.php │ ├── FileDeleteAction.php │ └── FileUploadAction.php └── FileUploadUI.php ├── CONTRIBUTING.md ├── composer.json ├── LICENSE.md └── README.md /src/views/gallery.php: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/views/uploadButton.php: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/messages/tr-TR/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Dosyaları Ekle', 8 | 'Start upload' => 'Yüklemeye Başla', 9 | 'Cancel upload' => 'Yüklemeyi İptal Et', 10 | 'Start' => 'Başla', 11 | 'Cancel' => 'İptal', 12 | 'Error' => 'Hata', 13 | 'Delete' => 'Sil', 14 | 'Processing' => 'İşleniyor', 15 | 'Select file...' => 'Dosya seç...', 16 | ]; 17 | -------------------------------------------------------------------------------- /src/BlueimpTmplAsset.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | class BlueimpTmplAsset extends AssetBundle 18 | { 19 | public $sourcePath = '@bower/blueimp-tmpl'; 20 | public $js = [ 21 | 'js/tmpl.min.js', 22 | ]; 23 | } 24 | -------------------------------------------------------------------------------- /src/BlueimpLoadImageAsset.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | class BlueimpLoadImageAsset extends AssetBundle 18 | { 19 | public $sourcePath = '@bower/blueimp-load-image'; 20 | public $js = [ 21 | 'js/load-image.all.min.js', 22 | ]; 23 | } 24 | -------------------------------------------------------------------------------- /src/BlueimpCanvasToBlobAsset.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | class BlueimpCanvasToBlobAsset extends AssetBundle 18 | { 19 | public $sourcePath = '@bower/blueimp-canvas-to-blob'; 20 | public $js = [ 21 | 'js/canvas-to-blob.min.js', 22 | ]; 23 | } 24 | -------------------------------------------------------------------------------- /src/messages/zh-TW/fileupload.php: -------------------------------------------------------------------------------- 1 | '添加文件', 22 | 'Start upload' => '開始上傳', 23 | 'Cancel upload' => '取消上傳', 24 | 'Start' => '開始', 25 | 'Cancel' => '取消', 26 | 'Error' => '錯誤', 27 | 'Delete' => '刪除', 28 | 'Processing' => '處理中', 29 | ]; -------------------------------------------------------------------------------- /src/messages/en/fileupload.php: -------------------------------------------------------------------------------- 1 | '', 22 | 'Start upload' => '', 23 | 'Cancel upload' => '', 24 | 'Start' => '', 25 | 'Cancel' => '', 26 | 'Error' => '', 27 | 'Delete' => '', 28 | 'Processing' => '', 29 | 'Select file...' => '' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/vi-VN/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Thêm file', 22 | 'Start upload' => 'Bắt đầu tải lên', 23 | 'Cancel upload' => 'Hủy tải lên', 24 | 'Start' => 'Bắt đầu', 25 | 'Cancel' => 'Hủy', 26 | 'Error' => 'Lỗi', 27 | 'Delete' => 'Xóa', 28 | 'Processing' => 'Đang xử lí', 29 | ]; -------------------------------------------------------------------------------- /src/messages/zh-CN/fileupload.php: -------------------------------------------------------------------------------- 1 | '添加文件', 22 | 'Start upload' => '开始上传', 23 | 'Cancel upload' => '取消上传', 24 | 'Start' => '开始', 25 | 'Cancel' => '取消', 26 | 'Error' => '错误', 27 | 'Delete' => '删除', 28 | 'Processing' => '正在处理', 29 | 'Select file...' => '选择文件...', 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/sk/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Pridať súbory', 21 | 'Start upload' => 'Spustiť nahrávanie', 22 | 'Cancel upload' => 'Zrušiť nahrávanie', 23 | 'Start' => 'Spustiť', 24 | 'Cancel' => 'Zrušiť', 25 | 'Error' => 'Chyba', 26 | 'Delete' => 'Vymazať', 27 | 'Processing' => 'Spracovanie', 28 | ]; 29 | -------------------------------------------------------------------------------- /src/FileUploadAsset.php: -------------------------------------------------------------------------------- 1 | 16 | * @author Semenov Alexander 17 | */ 18 | class FileUploadAsset extends AssetBundle 19 | { 20 | public $sourcePath = '@bower/blueimp-file-upload'; 21 | public $css = [ 22 | 'css/jquery.fileupload.css' 23 | ]; 24 | public $js = [ 25 | 'js/vendor/jquery.ui.widget.js', 26 | 'js/jquery.iframe-transport.js', 27 | 'js/jquery.fileupload.js' 28 | ]; 29 | public $depends = [ 30 | 'yii\web\JqueryAsset', 31 | 'yii\bootstrap\BootstrapAsset', 32 | ]; 33 | public $publishOptions = [ 34 | 'except' => [ 35 | 'server/*', 36 | 'test' 37 | ], 38 | ]; 39 | } 40 | -------------------------------------------------------------------------------- /src/messages/pt-PT/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Adicionar ficheiros', 22 | 'Start upload' => 'Iniciar upload', 23 | 'Cancel upload' => 'Cancelar upload', 24 | 'Start' => 'Iniciar', 25 | 'Cancel' => 'Cancelar', 26 | 'Error' => 'Erro', 27 | 'Delete' => 'Apagar', 28 | 'Processing' => 'A processar', 29 | ]; 30 | -------------------------------------------------------------------------------- /src/messages/he/fileupload.php: -------------------------------------------------------------------------------- 1 | 'הוספת קבצים', 22 | 'Start upload' => 'התחלת העלאה', 23 | 'Cancel upload' => 'ביטול העלאה', 24 | 'Start' => 'התחלה', 25 | 'Cancel' => 'ביטול', 26 | 'Error' => 'שגיאה', 27 | 'Delete' => 'מחיקה', 28 | 'Processing' => 'מעבד', 29 | 'Select file...' => 'בחר קובץ...' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/fa-IR/fileupload.php: -------------------------------------------------------------------------------- 1 | 'افزودن فایل‌ها', 22 | 'Start upload' => 'شروع آپلود', 23 | 'Cancel upload' => 'لغو آپلود', 24 | 'Start' => 'شروع', 25 | 'Cancel' => 'لغو', 26 | 'Error' => 'خطا', 27 | 'Delete' => 'حذف', 28 | 'Processing' => 'در حال پردازش', 29 | 'Select file...' => 'انتخاب فایل ...' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/it/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Aggiungi file', 22 | 'Start upload' => 'Inizia Upload', 23 | 'Cancel upload' => 'Annulla Upload', 24 | 'Start' => 'Inizia', 25 | 'Cancel' => 'Annulla', 26 | 'Error' => 'Errore', 27 | 'Delete' => 'Cancella', 28 | 'Processing' => 'In elaborazione', 29 | 'Select file...' => 'Seleziona file' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/fr/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Ajouter', 21 | 'Start upload' => 'Démarrer', 22 | 'Cancel upload' => 'Annuler', 23 | 'Start' => 'Démarrer', 24 | 'Cancel' => 'Annuler', 25 | 'Error' => 'Erreur', 26 | 'Delete' => 'Supprimer', 27 | 'Processing' => 'Chargement', 28 | 'Select file...' => 'Sélectionner un fichier...', 29 | ]; 30 | -------------------------------------------------------------------------------- /src/messages/pl/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Dodaj pliki', 22 | 'Start upload' => 'Wyślij', 23 | 'Cancel upload' => 'Anuluj wysyłanie', 24 | 'Start' => 'Start', 25 | 'Cancel' => 'Anuluj', 26 | 'Error' => 'Błąd', 27 | 'Delete' => 'Usuń', 28 | 'Processing' => 'Przetwarzanie', 29 | 'Select file...' => 'Wybierz plik...', 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/de/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Dateien hochladen', 22 | 'Start upload' => 'Upload starten', 23 | 'Cancel upload' => 'Upload abbrechen', 24 | 'Start' => 'Anfang', 25 | 'Cancel' => 'Abbrechen', 26 | 'Error' => 'Fehler', 27 | 'Delete' => 'Löschen', 28 | 'Processing' => 'Verarbeitung', 29 | 'Select file...' => 'Dateien auswählen' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/nl/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Kies bestanden', 22 | 'Start upload' => 'Start upload', 23 | 'Cancel upload' => 'Annuleer upload', 24 | 'Start' => 'Start', 25 | 'Cancel' => 'Annuleer', 26 | 'Error' => 'Error', 27 | 'Delete' => 'Verwijderen', 28 | 'Processing' => 'Bezig', 29 | 'Select file...' => 'Kies bestand...' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/bg/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Добави файлове', 22 | 'Start upload' => 'Започни качване', 23 | 'Cancel upload' => 'Отмени качването', 24 | 'Start' => 'Започни', 25 | 'Cancel' => 'Отмени', 26 | 'Error' => 'Грешка', 27 | 'Delete' => 'Изтрий', 28 | 'Processing' => 'Обработване', 29 | 'Select file...' => 'Избери файл...' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/ru/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Добавить файлы', 22 | 'Start upload' => 'Начать загрузку', 23 | 'Cancel upload' => 'Отменить загрузку', 24 | 'Start' => 'Загрузить', 25 | 'Cancel' => 'Отмена', 26 | 'Error' => 'Ошибка', 27 | 'Delete' => 'Удалить', 28 | 'Processing' => 'Загрузка', 29 | 'Select file...' => 'Выбрать файл', 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/lv/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Pievienot failus', 22 | 'Start upload' => 'Sākt augšupielādi', 23 | 'Cancel upload' => 'Atcelt augšupielādi', 24 | 'Start' => 'Sākt', 25 | 'Cancel' => 'Atcelt', 26 | 'Error' => 'Kļūda', 27 | 'Delete' => 'Dzēst', 28 | 'Processing' => 'Apstrādā', 29 | 'Select file...' => 'Izvēlēties failu...' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/es-MX/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Agregar archivos', 22 | 'Start upload' => 'Iniciar subida', 23 | 'Cancel upload' => 'Cancelar subida', 24 | 'Start' => 'Iniciar', 25 | 'Cancel' => 'Cancelar', 26 | 'Error' => 'Error', 27 | 'Delete' => 'Eliminar', 28 | 'Processing' => 'Procesando', 29 | 'Select file...' => 'Selecciona archivo...' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/es/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Agregar archivos', 22 | 'Start upload' => 'Iniciar subida', 23 | 'Cancel upload' => 'Cancelar subida', 24 | 'Start' => 'Iniciar', 25 | 'Cancel' => 'Cancelar', 26 | 'Error' => 'Error', 27 | 'Delete' => 'Eliminar', 28 | 'Processing' => 'Procesando', 29 | 'Select file...' => 'Selecciona archivo...' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/pt-BR/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Adicionar arquivos', 22 | 'Start upload' => 'Iniciar envio', 23 | 'Cancel upload' => 'Cancelar envio', 24 | 'Start' => 'Iniciar', 25 | 'Cancel' => 'Cancelar', 26 | 'Error' => 'Erro', 27 | 'Delete' => 'Apagar', 28 | 'Processing' => 'Processando', 29 | 'Select file...' => 'Selecione o arquivo...' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/el/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Προσθήκη αρχείων', 22 | 'Start upload' => 'Έναρξη μεταφόρτωσης', 23 | 'Cancel upload' => 'Ακύρωση μεταφόρτωσης', 24 | 'Start' => 'Έναρξη', 25 | 'Cancel' => 'Ακύρωση', 26 | 'Error' => 'Λάθος', 27 | 'Delete' => 'Διαγραφή', 28 | 'Processing' => 'Επεξεργασία', 29 | 'Select file...' => 'Επιλέξτε αρχείο...' 30 | ]; 31 | -------------------------------------------------------------------------------- /src/messages/uz-UZ/fileupload.php: -------------------------------------------------------------------------------- 1 | 'Fayllarni qo\'shish', 22 | 'Start upload' => 'Yuklashni boshlash', 23 | 'Cancel upload' => 'Yuklashni bekor qilish', 24 | 'Start' => 'Yuklash', 25 | 'Cancel' => 'Bekor qilish', 26 | 'Error' => 'Hato', 27 | 'Delete' => 'O\'chirish', 28 | 'Processing' => 'Yuklanmoqda', 29 | 'Select file...' => 'Faylni tanlash', 30 | ]; 31 | -------------------------------------------------------------------------------- /src/FileUploadPlusAsset.php: -------------------------------------------------------------------------------- 1 | 16 | * @author Semenov Alexander 17 | */ 18 | class FileUploadPlusAsset extends AssetBundle 19 | { 20 | public $sourcePath = '@bower/blueimp-file-upload'; 21 | public $css = [ 22 | 'css/jquery.fileupload.css' 23 | ]; 24 | public $js = [ 25 | 'js/jquery.iframe-transport.js', 26 | 'js/jquery.fileupload-process.js', 27 | 'js/jquery.fileupload-image.js', 28 | 'js/jquery.fileupload-audio.js', 29 | 'js/jquery.fileupload-video.js', 30 | 'js/jquery.fileupload-validate.js' 31 | ]; 32 | public $depends = [ 33 | 'dosamigos\fileupload\FileUploadAsset', 34 | 'dosamigos\fileupload\BlueimpLoadImageAsset', 35 | 'dosamigos\fileupload\BlueimpCanvasToBlobAsset', 36 | ]; 37 | public $publishOptions = [ 38 | 'except' => [ 39 | 'server/*', 40 | 'test' 41 | ], 42 | ]; 43 | } 44 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | We accept contributions via Pull Requests on [Github](https://github.com/2amigos/yii2-selectize-widget). 6 | 7 | 8 | ## Pull Requests 9 | 10 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). 11 | 12 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 13 | 14 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 15 | 16 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 17 | 18 | - **Create feature branches** - Don't ask us to pull from your master branch. 19 | 20 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 21 | 22 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. 23 | 24 | 25 | ## Running Tests 26 | 27 | ``` bash 28 | $ ./vendor/bin/phpunit 29 | ``` 30 | 31 | 32 | **Happy coding**! 33 | -------------------------------------------------------------------------------- /src/views/upload.php: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "2amigos/yii2-file-upload-widget", 3 | "description": "Blueimp file upload widget for the Yii framework", 4 | "keywords": [ 5 | "2amigos", 6 | "yii", 7 | "yii2", 8 | "yii 2", 9 | "widget", 10 | "upload" 11 | ], 12 | "type": "yii2-extension", 13 | "license": "BSD-3-Clause", 14 | "homepage": "https://github.com/2amigos/yii2-file-upload-widget", 15 | "authors": [ 16 | { 17 | "name": "2amigOS! Consulting Group", 18 | "email": "hola@2amigos.us", 19 | "homepage": "http://2amigos.us", 20 | "role": "Developer" 21 | } 22 | ], 23 | "require": { 24 | "yiisoft/yii2": "^2.0.0", 25 | "yiisoft/yii2-bootstrap": "^2.0.0", 26 | "2amigos/yii2-gallery-widget": "^1.0", 27 | "bower-asset/blueimp-file-upload": "^9.9" 28 | }, 29 | "require-dev": { 30 | "phpunit/phpunit": "~4.0", 31 | "roave/security-advisories": "dev-master" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "dosamigos\\fileupload\\": "src" 36 | } 37 | }, 38 | "config": { 39 | "fxp-asset": { 40 | "installer-paths": { 41 | "npm-asset-library": "vendor/npm", 42 | "bower-asset-library": "vendor/bower" 43 | } 44 | } 45 | }, 46 | "extra": { 47 | "branch-alias": { 48 | "dev-master": "1.0-dev" 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/FileUploadUIAsset.php: -------------------------------------------------------------------------------- 1 | 16 | * @author Semenov Alexander 17 | */ 18 | class FileUploadUIAsset extends AssetBundle 19 | { 20 | public $sourcePath = '@bower/blueimp-file-upload'; 21 | public $css = [ 22 | 'css/jquery.fileupload.css' 23 | ]; 24 | public $js = [ 25 | 'js/vendor/jquery.ui.widget.js', 26 | 'js/jquery.iframe-transport.js', 27 | 'js/jquery.fileupload.js', 28 | 'js/jquery.fileupload-process.js', 29 | 'js/jquery.fileupload-image.js', 30 | 'js/jquery.fileupload-audio.js', 31 | 'js/jquery.fileupload-video.js', 32 | 'js/jquery.fileupload-validate.js', 33 | 'js/jquery.fileupload-ui.js', 34 | 35 | ]; 36 | public $depends = [ 37 | 'yii\web\JqueryAsset', 38 | 'yii\bootstrap\BootstrapPluginAsset', 39 | 'dosamigos\fileupload\BlueimpLoadImageAsset', 40 | 'dosamigos\fileupload\BlueimpCanvasToBlobAsset', 41 | 'dosamigos\fileupload\BlueimpTmplAsset' 42 | ]; 43 | public $publishOptions = [ 44 | 'except' => [ 45 | 'server/*', 46 | 'test' 47 | ], 48 | ]; 49 | } 50 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # The BSD License (BSD) 2 | 3 | Copyright (c) 2013-2015, 2amigOS! Consulting Group LLC. 4 | 5 | > Redistribution and use in source and binary forms, with or without modification, 6 | > are permitted provided that the following conditions are met: 7 | > 8 | > Redistributions of source code must retain the above copyright notice, this 9 | > list of conditions and the following disclaimer. 10 | > 11 | > Redistributions in binary form must reproduce the above copyright notice, this 12 | > list of conditions and the following disclaimer in the documentation and/or 13 | > other materials provided with the distribution. 14 | > 15 | > Neither the name of 2amigOS! Consulting Group, LLC. nor the names of its 16 | > contributors may be used to endorse or promote products derived from 17 | > this software without specific prior written permission. 18 | > 19 | >THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | >ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | >WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | >DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 23 | >ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | >(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | >LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 26 | >ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | >(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | >SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /src/views/download.php: -------------------------------------------------------------------------------- 1 | 2 | 45 | -------------------------------------------------------------------------------- /src/BaseUpload.php: -------------------------------------------------------------------------------- 1 | 19 | */ 20 | class BaseUpload extends InputWidget 21 | { 22 | /** 23 | * @var string|array upload route 24 | */ 25 | public $url; 26 | /** 27 | * @var array the plugin options. For more information see the jQuery File Upload options documentation. 28 | * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options 29 | */ 30 | public $clientOptions = []; 31 | /** 32 | * @var array the event handlers for the jQuery File Upload plugin. 33 | * Please refer to the jQuery File Upload plugin web page for possible options. 34 | * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#callback-options 35 | */ 36 | public $clientEvents = []; 37 | /** 38 | * @var array for the internalization configuration 39 | */ 40 | public $i18n = []; 41 | 42 | /** 43 | * @inheritdoc 44 | * @throws \yii\base\InvalidConfigException 45 | */ 46 | public function init() 47 | { 48 | parent::init(); 49 | $this->initI18N(); 50 | 51 | if(empty($this->url)) { 52 | throw new InvalidConfigException('"url" cannot be empty.'); 53 | } 54 | 55 | $this->clientOptions['url'] = Url::to($this->url); 56 | } 57 | 58 | /** 59 | * Initialize internalization 60 | */ 61 | public function initI18N() 62 | { 63 | Yii::setAlias('@fileupload', dirname(__FILE__)); 64 | if (empty($this->i18n)) { 65 | $this->i18n = [ 66 | 'sourceLanguage' => 'en', 67 | 'basePath' => '@fileupload/messages', 68 | 'class' => 'yii\i18n\PhpMessageSource', 69 | ]; 70 | } 71 | Yii::$app->i18n->translations['fileupload'] = $this->i18n; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/FileUpload.php: -------------------------------------------------------------------------------- 1 | 20 | */ 21 | class FileUpload extends BaseUpload 22 | { 23 | /** 24 | * @var bool whether to register the js files for the basic + 25 | */ 26 | public $plus = false; 27 | 28 | /** 29 | * @var bool whether to render the default button 30 | */ 31 | public $useDefaultButton = true; 32 | 33 | /** 34 | * @var string the upload view path to render the js upload template 35 | */ 36 | public $uploadButtonTemplateView = 'uploadButton'; 37 | 38 | /** 39 | * @inheritdoc 40 | */ 41 | public function init() 42 | { 43 | parent::init(); 44 | 45 | $url = Url::to($this->url); 46 | $this->options['data-url'] = $url; 47 | } 48 | 49 | /** 50 | * @inheritdoc 51 | */ 52 | public function run() 53 | { 54 | $input = $this->hasModel() 55 | ? Html::activeFileInput($this->model, $this->attribute, $this->options) 56 | : Html::fileInput($this->name, $this->value, $this->options); 57 | 58 | echo $this->useDefaultButton 59 | ? $this->render($this->uploadButtonTemplateView, ['input' => $input]) 60 | : $input; 61 | 62 | $this->registerClientScript(); 63 | } 64 | 65 | /** 66 | * Registers required script for the plugin to work as jQuery File Uploader 67 | */ 68 | public function registerClientScript() 69 | { 70 | $view = $this->getView(); 71 | 72 | if($this->plus) { 73 | FileUploadPlusAsset::register($view); 74 | } else { 75 | FileUploadAsset::register($view); 76 | } 77 | 78 | $options = Json::encode($this->clientOptions); 79 | $id = $this->options['id']; 80 | 81 | $js[] = ";jQuery('#$id').fileupload($options);"; 82 | if (!empty($this->clientEvents)) { 83 | foreach ($this->clientEvents as $event => $handler) { 84 | $js[] = "jQuery('#$id').on('$event', $handler);"; 85 | } 86 | } 87 | $view->registerJs(implode("\n", $js)); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/views/form.php: -------------------------------------------------------------------------------- 1 | context; 6 | ?> 7 | 8 | options); ?> 9 | 10 |
11 |
12 | 13 | 14 | 15 | ... 16 | 17 | model instanceof \yii\base\Model && $context->attribute !== null 18 | ? Html::activeFileInput($context->model, $context->attribute, $context->fieldOptions) 19 | : Html::fileInput($context->name, $context->value, $context->fieldOptions);?> 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 |
38 | 39 |
40 | 41 |
42 |
43 |
44 | 45 |
 
46 |
47 |
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/actions/FileListAction.php: -------------------------------------------------------------------------------- 1 | 18 | * @package dosamigos\fileupload\actions 19 | */ 20 | class FileListAction extends Action 21 | { 22 | /** 23 | * @var string the full qualified namespace name of the model's search class -ie `\common\models\PictureSearch` 24 | */ 25 | public $searchClass; 26 | /** 27 | * @var string the owner relation name of the model's class -ie `Picture::cities`, cities is the relation name of 28 | * `Picture` class to links to its owner, on this case `City` model. 29 | */ 30 | public $ownerRelation; 31 | /** 32 | * @var string the owner table name -ie `city` 33 | */ 34 | public $ownerTable; 35 | /** 36 | * @var string the name of the view where the resulting `$dataProvider` attribute will be pass through. 37 | */ 38 | public $view; 39 | 40 | /** 41 | * @inheritdoc 42 | * @throws InvalidConfigException 43 | */ 44 | public function init() 45 | { 46 | if (!isset($this->ownerRelation, $this->ownerTable, $this->searchClass, $this->view)) { 47 | throw new InvalidConfigException( 48 | '"searchClass", "ownerRelation", "ownerTable" and "view" attributes cannot be null' 49 | ); 50 | } 51 | parent::init(); 52 | } 53 | 54 | /** 55 | * Builds the data provider that needs to be rendered. If you wish to modify it, you will have to do it on the 56 | * view itself -ie change pager settings etc. 57 | * 58 | * @inheritdoc 59 | * @throws NotFoundHttpException 60 | */ 61 | public function run() 62 | { 63 | $ownerId = Yii::$app->request->get('ownerId'); 64 | if (!$ownerId) { 65 | throw new NotFoundHttpException(); 66 | } 67 | $searchClass = new $this->searchClass(); 68 | $searchClass->innerJoinWith = [ 69 | $this->ownerRelation => function ($q) use ($ownerId) { 70 | $q->andWhere([$this->ownerTable . ".id" => $ownerId]); 71 | } 72 | ]; 73 | $method = Yii::$app->request->isPjax ? 'renderAjax' : 'render'; 74 | 75 | $this->controller->{$method}($this->view, ['ownerId' => $ownerId, 'dataProvider' => $searchClass->search([])]); 76 | 77 | throw new NotFoundHttpException(Yii::t('fileupload', 'Page not found')); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/FileUploadUI.php: -------------------------------------------------------------------------------- 1 | 21 | */ 22 | class FileUploadUI extends BaseUpload 23 | { 24 | /** 25 | * @var bool whether to use the Bootstrap Gallery on the images or not 26 | */ 27 | public $gallery = true; 28 | /** 29 | * @var bool load previously uploaded images or not 30 | */ 31 | public $load = false; 32 | /** 33 | * @var array the HTML attributes for the file input tag. 34 | * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered. 35 | */ 36 | public $fieldOptions = []; 37 | /** 38 | * @var string the ID of the upload template, given as parameter to the tmpl() method to set the uploadTemplate option. 39 | */ 40 | public $uploadTemplateId; 41 | /** 42 | * @var string the ID of the download template, given as parameter to the tmpl() method to set the downloadTemplate option. 43 | */ 44 | public $downloadTemplateId; 45 | /** 46 | * @var string the form view path to render the JQuery File Upload UI 47 | */ 48 | public $formView = 'form'; 49 | /** 50 | * @var string the upload view path to render the js upload template 51 | */ 52 | public $uploadTemplateView = 'upload'; 53 | /** 54 | * @var string the download view path to render the js download template 55 | */ 56 | public $downloadTemplateView = 'download'; 57 | /** 58 | * @var string the gallery 59 | */ 60 | public $galleryTemplateView = 'gallery'; 61 | 62 | 63 | /** 64 | * @inheritdoc 65 | */ 66 | public function init() 67 | { 68 | parent::init(); 69 | 70 | $this->fieldOptions['multiple'] = true; 71 | $this->fieldOptions['id'] = ArrayHelper::getValue($this->options, 'id'); 72 | 73 | $this->options['id'] .= '-fileupload'; 74 | $this->options['data-upload-template-id'] = $this->uploadTemplateId ? : 'template-upload'; 75 | $this->options['data-download-template-id'] = $this->downloadTemplateId ? : 'template-download'; 76 | } 77 | 78 | /** 79 | * @inheritdoc 80 | */ 81 | public function run() 82 | { 83 | echo $this->render($this->uploadTemplateView); 84 | echo $this->render($this->downloadTemplateView); 85 | echo $this->render($this->formView); 86 | 87 | if ($this->gallery) { 88 | echo $this->render($this->galleryTemplateView); 89 | } 90 | 91 | $this->registerClientScript(); 92 | } 93 | 94 | /** 95 | * Registers required script for the plugin to work as jQuery File Uploader UI 96 | */ 97 | public function registerClientScript() 98 | { 99 | $view = $this->getView(); 100 | 101 | if ($this->gallery) { 102 | GalleryAsset::register($view); 103 | } 104 | 105 | FileUploadUIAsset::register($view); 106 | 107 | $options = Json::encode($this->clientOptions); 108 | $id = $this->options['id']; 109 | 110 | $js[] = ";jQuery('#$id').fileupload($options);"; 111 | if (!empty($this->clientEvents)) { 112 | foreach ($this->clientEvents as $event => $handler) { 113 | $js[] = "jQuery('#$id').on('$event', $handler);"; 114 | } 115 | } 116 | $view->registerJs(implode("\n", $js)); 117 | 118 | if ($this->load) { 119 | $view->registerJs(" 120 | $('#$id').addClass('fileupload-processing'); 121 | $.ajax({ 122 | url: $('#$id').fileupload('option', 'url'), 123 | dataType: 'json', 124 | context: $('#$id')[0] 125 | }).always(function () { 126 | $(this).removeClass('fileupload-processing'); 127 | }).done(function (result) { 128 | $(this).fileupload('option', 'done').call(this, $.Event('done'), {result: result}); 129 | }); 130 | "); 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/actions/FileDeleteAction.php: -------------------------------------------------------------------------------- 1 | 20 | */ 21 | class FileDeleteAction extends Action 22 | { 23 | /** 24 | * @var string the AR class name that we need to delete 25 | */ 26 | public $className; 27 | /** 28 | * @var string the parameter name in the request. Defaults to 'id'. 29 | */ 30 | public $idParamName = 'id'; 31 | /** 32 | * @var string the name of the table handling relations -ie city_picture_assn 33 | */ 34 | public $ownerLinkTable; 35 | /** 36 | * @var string the name of the attribute of the class we are going to delete -ie picture_id 37 | */ 38 | public $ownerLinkTableAttribute; 39 | /** 40 | * @var string|array the route to redirect after successful deletion. Note: If the user is doing and AJAX'ed 41 | * request. Will simply return a JSON with `success` true or false. If `success` it will contain a `message`, 42 | * otherwise will contain also `errors` key so you can display the issues on a notification plugin or whatever. 43 | */ 44 | public $redirectRoute = 'index'; 45 | 46 | /** 47 | * @inheritdoc 48 | * @throws InvalidConfigException 49 | */ 50 | public function init() 51 | { 52 | if (!isset($this->ownerLinkTable, $this->className)) { 53 | throw new InvalidConfigException('"ownerLinkTable" and "className" attributes cannot be null'); 54 | } 55 | parent::init(); 56 | } 57 | 58 | /** 59 | * @inheritdoc 60 | * 61 | * @return array|Response 62 | * @throws NotFoundHttpException 63 | */ 64 | public function run() 65 | { 66 | $id = Yii::$app->request->get($this->idParamName); 67 | if (!$id) { 68 | throw new NotFoundHttpException(Yii::t('fileupload', 'Page not found')); 69 | } 70 | $model = call_user_func([$this->className, 'findOne'], $id); 71 | $response = ['success' => $model->delete()]; 72 | 73 | if (Yii::$app->request->isPost) { 74 | 75 | $shortClassName = (strpos($this->className, '\\') === false 76 | ? $this->className 77 | : substr($this->className, strrpos($this->className, '\\') + 1)); 78 | 79 | if (Yii::$app->request->isAjax) { // handling AJAX'ed requests 80 | 81 | Yii::$app->response->format = Response::FORMAT_JSON; 82 | $response['success'] = $model->delete(); 83 | if ($response['success']) { 84 | $this->unlink($id); 85 | $response['message'] = $shortClassName . ' ' . Yii::t('fileupload', 'successfully removed.'); 86 | } else { 87 | $response['message'] = Yii::t('fileupload', 'Unable to remove') . $shortClassName; 88 | $response['errors'] = implode("\n", $this->getModelErrors($model)); 89 | } 90 | 91 | return $response; 92 | 93 | } else { // handling not AJAX'ed requests 94 | 95 | if ($model->delete()) { 96 | Yii::$app->session->addFlash( 97 | 'success', 98 | $shortClassName . ' ' . Yii::t('fileupload', 'successfully removed.') 99 | ); 100 | } else { 101 | Yii::$app->session->addFlash('error', Yii::t('fileupload', 'Unable to remove') . $shortClassName); 102 | } 103 | } 104 | } 105 | 106 | return $this->controller->redirect($this->redirectRoute); 107 | 108 | } 109 | 110 | /** 111 | * Removed 112 | * 113 | * @param mixed $id the id of the class to remove from link table 114 | */ 115 | protected function unlink($id) 116 | { 117 | ActiveRecord::getDb() 118 | ->createCommand() 119 | ->delete($this->ownerLinkTable, [$this->ownerLinkTableAttribute => $id]) 120 | ->execute(); 121 | } 122 | 123 | /** 124 | * Helper function 125 | * 126 | * @param \yii\base\Model $model 127 | * 128 | * @return array 129 | * @todo breaks DRY. Think of the best way to implement. 130 | */ 131 | protected function getModelErrors($model) 132 | { 133 | $errors = []; 134 | foreach ($model->getFirstErrors() as $error) { 135 | $errors[] = $error; 136 | } 137 | 138 | return $errors; 139 | } 140 | 141 | } 142 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BlueImp File Upload Widget for Yii2 2 | 3 | [![Latest Version](https://img.shields.io/github/tag/2amigos/yii2-file-upload-widget.svg?style=flat-square&label=release)](https://github.com/2amigos/yii2-file-upload-widget/tags) 4 | [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) 5 | [![Build Status](https://img.shields.io/travis/2amigos/yii2-file-upload-widget/master.svg?style=flat-square)](https://travis-ci.org/2amigos/yii2-file-upload-widget) 6 | [![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/2amigos/yii2-file-upload-widget.svg?style=flat-square)](https://scrutinizer-ci.com/g/2amigos/yii2-file-upload-widget/code-structure) 7 | [![Quality Score](https://img.shields.io/scrutinizer/g/2amigos/yii2-file-upload-widget.svg?style=flat-square)](https://scrutinizer-ci.com/g/2amigos/yii2-file-upload-widget) 8 | [![Total Downloads](https://img.shields.io/packagist/dt/2amigos/yii2-file-upload-widget.svg?style=flat-square)](https://packagist.org/packages/2amigos/yii2-file-upload-widget) 9 | 10 | Renders a [BlueImp jQuery File Upload plugin](http://blueimp.github.io/jQuery-File-Upload/). That plugin integrates multiple file selection, drag&drop support, progress bars, validation and preview of images. 11 | 12 | ## Installation 13 | 14 | The preferred way to install this extension is through [composer](http://getcomposer.org/download/). 15 | 16 | Either run 17 | 18 | ```bash 19 | $ composer require 2amigos/yii2-file-upload-widget:~1.0 20 | ``` 21 | 22 | or add 23 | 24 | ``` 25 | "2amigos/yii2-file-upload-widget": "~1.0" 26 | ``` 27 | 28 | to the `require` section of your `composer.json` file. 29 | 30 | ## Usage 31 | 32 | The widget comes with two flavors: 33 | 34 | - FileUpload: [Basic](http://blueimp.github.io/jQuery-File-Upload/basic.html) and [BasicPlus](http://blueimp.github.io/jQuery-File-Upload/basic-plus.html) 35 | - FileUploadUI: [BasicPlus UI](http://blueimp.github.io/jQuery-File-Upload/index.html) 36 | 37 | ```PHP 38 | 43 | 44 | $model, 46 | 'attribute' => 'image', 47 | 'url' => ['media/upload', 'id' => $model->id], // your url, this is just for demo purposes, 48 | 'options' => ['accept' => 'image/*'], 49 | 'clientOptions' => [ 50 | 'maxFileSize' => 2000000 51 | ], 52 | // Also, you can specify jQuery-File-Upload events 53 | // see: https://github.com/blueimp/jQuery-File-Upload/wiki/Options#processing-callback-options 54 | 'clientEvents' => [ 55 | 'fileuploaddone' => 'function(e, data) { 56 | console.log(e); 57 | console.log(data); 58 | }', 59 | 'fileuploadfail' => 'function(e, data) { 60 | console.log(e); 61 | console.log(data); 62 | }', 63 | ], 64 | ]); ?> 65 | 66 | 71 | $model, 73 | 'attribute' => 'image', 74 | 'url' => ['media/upload', 'id' => $tour_id], 75 | 'gallery' => false, 76 | 'fieldOptions' => [ 77 | 'accept' => 'image/*' 78 | ], 79 | 'clientOptions' => [ 80 | 'maxFileSize' => 2000000 81 | ], 82 | // ... 83 | 'clientEvents' => [ 84 | 'fileuploaddone' => 'function(e, data) { 85 | console.log(e); 86 | console.log(data); 87 | }', 88 | 'fileuploadfail' => 'function(e, data) { 89 | console.log(e); 90 | console.log(data); 91 | }', 92 | ], 93 | ]); ?> 94 | 95 | session->id . DIRECTORY_SEPARATOR; 106 | if (!is_dir($directory)) { 107 | FileHelper::createDirectory($directory); 108 | } 109 | 110 | if ($imageFile) { 111 | $uid = uniqid(time(), true); 112 | $fileName = $uid . '.' . $imageFile->extension; 113 | $filePath = $directory . $fileName; 114 | if ($imageFile->saveAs($filePath)) { 115 | $path = '/img/temp/' . Yii::$app->session->id . DIRECTORY_SEPARATOR . $fileName; 116 | return Json::encode([ 117 | 'files' => [ 118 | [ 119 | 'name' => $fileName, 120 | 'size' => $imageFile->size, 121 | 'url' => $path, 122 | 'thumbnailUrl' => $path, 123 | 'deleteUrl' => 'image-delete?name=' . $fileName, 124 | 'deleteType' => 'POST', 125 | ], 126 | ], 127 | ]); 128 | } 129 | } 130 | 131 | return ''; 132 | } 133 | 134 | public function actionImageDelete($name) 135 | { 136 | $directory = Yii::getAlias('@frontend/web/img/temp') . DIRECTORY_SEPARATOR . Yii::$app->session->id; 137 | if (is_file($directory . DIRECTORY_SEPARATOR . $name)) { 138 | unlink($directory . DIRECTORY_SEPARATOR . $name); 139 | } 140 | 141 | $files = FileHelper::findFiles($directory); 142 | $output = []; 143 | foreach ($files as $file) { 144 | $fileName = basename($file); 145 | $path = '/img/temp/' . Yii::$app->session->id . DIRECTORY_SEPARATOR . $fileName; 146 | $output['files'][] = [ 147 | 'name' => $fileName, 148 | 'size' => filesize($file), 149 | 'url' => $path, 150 | 'thumbnailUrl' => $path, 151 | 'deleteUrl' => 'image-delete?name=' . $fileName, 152 | 'deleteType' => 'POST', 153 | ]; 154 | } 155 | return Json::encode($output); 156 | } 157 | ``` 158 | 159 | Please, check the [jQuery File Upload documentation](https://github.com/blueimp/jQuery-File-Upload/wiki) for further information about its configuration options. 160 | 161 | 162 | ## Using the Actions 163 | TODO 164 | 165 | ## Testing 166 | 167 | ```bash 168 | $ ./vendor/bin/phpunit 169 | ``` 170 | 171 | ## Contributing 172 | 173 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 174 | 175 | ## Credits 176 | 177 | - [Antonio Ramirez](https://github.com/tonydspaniard) 178 | - [All Contributors](https://github.com/2amigos/yii2-file-upload-widget/graphs/contributors) 179 | 180 | ## License 181 | 182 | The BSD License (BSD). Please see [License File](LICENSE.md) for more information. 183 | 184 |
185 |
186 | web development has never been so fun
187 | www.2amigos.us 188 |
189 | -------------------------------------------------------------------------------- /src/actions/FileUploadAction.php: -------------------------------------------------------------------------------- 1 | 25 | * @package dosamigos\fileupload\actions 26 | */ 27 | class FileUploadAction extends Action 28 | { 29 | /** 30 | * @var string the AR class name that we need to link the uploaded instance to 31 | */ 32 | public $className; 33 | /** 34 | * @var string the attribute name the class is using to upload files 35 | */ 36 | public $uploadAttributeName; 37 | /** 38 | * @var string the attribute name of the class that validates the uploaded files 39 | */ 40 | public $fileAttributeName; 41 | /** 42 | * @var string the attribute name of the class that will contain the web url reference -ie url 43 | */ 44 | public $urlAttributeName = 'url'; 45 | /** 46 | * @var string the attribute name of the class that will contain thumbnail's web url reference -ie thumbnail. 47 | * Could also be `url` but then make sure the resize is correct. 48 | */ 49 | public $thumbnailUrlAttributeName = 'thumbnail'; 50 | /** 51 | * @var string the owner table link -ie city_picture_assn 52 | */ 53 | public $ownerLinkTable; 54 | /** 55 | * @var string the owner's attribute in the table link -ie city_id 56 | */ 57 | public $ownerLinkTableOwnerAttribute; 58 | /** 59 | * @var string the name of the attribute of the class we are going to upload and link -ie picture_id 60 | */ 61 | public $ownerLinkTableAttribute; 62 | /** 63 | * @var string the parameter name where we can get the owner id. Defaults to 'ownerId' 64 | */ 65 | public $ownerIdParamName = 'ownerId'; 66 | /** 67 | * @var array the parameter name so to add the delete 68 | */ 69 | public $deleteUrlRoute = ['delete']; 70 | /** 71 | * @var string the parameter name to pass to the delete Url route 72 | */ 73 | public $deleteIdParamName = 'id'; 74 | /** 75 | * @var string the web url where they are stored. -ie http://myexample.com/files 76 | */ 77 | public $filesWebUrl; 78 | /** 79 | * @var string the path alias where to upload the files. -ie @frontend/web/files 80 | */ 81 | public $filePathAlias; 82 | 83 | /** 84 | * @inheritdoc 85 | * @throws InvalidConfigException 86 | */ 87 | public function init() 88 | { 89 | if (!isset($this->className, $this->ownerLinkTableOwnerAttribute, $this->ownerLinkTable, $this->ownerLinkTableAttribute)) { 90 | throw new InvalidConfigException( 91 | '"className", "ownerLinkTableOwnerAttribute", "ownerLinkAttribute" and "ownerLinkTable" cannot be null' 92 | ); 93 | } 94 | parent::init(); 95 | } 96 | 97 | /** 98 | * @inheritdoc 99 | * 100 | * @return array 101 | * @throws HttpException 102 | * @throws NotFoundHttpException 103 | */ 104 | public function run() 105 | { 106 | $ownerId = Yii::$app->request->get($this->ownerIdParamName); 107 | if (!$ownerId) { 108 | throw new NotFoundHttpException(Yii::t('fileupload', 'Page not found')); 109 | } 110 | /** @var ActiveRecord $model */ 111 | $model = new $this->className(); 112 | $model->{$this->fileAttributeName} = UploadedFile::getInstance($model, $this->uploadAttributeName); 113 | 114 | if (isset($model->{$this->fileAttributeName}) && $model->validate($this->{$this->fileAttributeName})) { 115 | 116 | Yii::$app->response->getHeaders()->set('Vary', 'Accept'); 117 | Yii::$app->response->format = Response::FORMAT_JSON; 118 | 119 | $response = []; 120 | $filePath = null; 121 | $transaction = ActiveRecord::getDb()->beginTransaction(); 122 | 123 | try { 124 | $this->upload($model); 125 | $deleteRoute = $this->deleteUrlRoute + [$this->deleteIdParamName => $model->id]; 126 | $response['files'][] = [ 127 | 'name' => $model->{$this->fileAttributeName}->name, 128 | 'type' => $model->{$this->fileAttributeName}->type, 129 | 'size' => $model->{$this->fileAttributeName}->size, 130 | 'url' => $model->{$this->urlAttributeName}, 131 | 'thumbnailUrl' => $model->{$this->thumbnailUrlAttributeName}, 132 | 'deleteUrl' => Url::to($deleteRoute), 133 | 'deleteType' => 'POST' 134 | ]; 135 | 136 | $this->link($ownerId, $model->id); 137 | 138 | $transaction->commit(); 139 | } catch (Exception $e) { 140 | $transaction->rollBack(); 141 | $response[] = [ 142 | 'error' => Yii::t( 143 | 'fileupload', 144 | 'Unable to save picture: `{errorMessage}`', 145 | ['errorMessage' => $e->getMessage()] 146 | ), 147 | ]; 148 | 149 | @unlink($model->{$this->fileAttributeName}->tempName); 150 | } 151 | } else { 152 | if ($model->hasErrors([$this->fileAttributeName])) { 153 | $response[] = ['errors' => $this->getModelErrors($model)]; 154 | } else { 155 | throw new HttpException(500, Yii::t('fileupload', 'Could not upload file.')); 156 | } 157 | } 158 | 159 | return $response; 160 | } 161 | 162 | /** 163 | * Links uploaded file to its owner. 164 | * 165 | * @param mixed $ownerId 166 | * @param mixed $id 167 | */ 168 | protected function link($ownerId, $id) 169 | { 170 | ActiveRecord::getDb() 171 | ->createCommand() 172 | ->insert( 173 | $this->ownerLinkTable, 174 | [$this->ownerLinkTableAttribute => $ownerId, $this->ownerLinkTableAttribute => $id] 175 | ) 176 | ->execute(); 177 | } 178 | 179 | /** 180 | * Helper function 181 | * 182 | * @param \yii\base\Model $model 183 | * 184 | * @return array 185 | * @todo breaks DRY. Think of the best way to implement. 186 | */ 187 | protected function getModelErrors($model) 188 | { 189 | $errors = []; 190 | foreach ($model->getFirstErrors() as $error) { 191 | $errors[] = $error; 192 | } 193 | 194 | return $errors; 195 | } 196 | 197 | /** 198 | * Handles files upload Override as needed. 199 | * 200 | * @param ActiveRecord $model 201 | * 202 | * @return mixed 203 | * 204 | * @throws Exception 205 | */ 206 | protected function upload($model) 207 | { 208 | /** @var UploadedFile $file */ 209 | $file = $model->{$this->fileAttributeName}; 210 | $path = Yii::getAlias($this->filePathAlias); 211 | $filename = md5(mt_rand()) . "-{$file->baseName}.{$file->extension}"; 212 | 213 | if (!$file->saveAs($path . '/' . $filename)) { 214 | throw new Exception(Yii::t('fileupload', 'Cannot save uploaded file')); 215 | } 216 | $model->{$this->urlAttributeName} = $this->filesWebUrl . '/' . $filename; 217 | // thumbnail url is the same as the url. Extend from this class and override this method 218 | // to implement your thumbnail logic. 219 | $model->{$this->thumbnailUrlAttributeName} = $model->{$this->urlAttributeName}; 220 | 221 | if (!$model->save(false)) { 222 | @unlink($path . '/' . $filename); 223 | throw new Exception(Yii::t('fileupload', 'Cannot save file model.')); 224 | } 225 | } 226 | } 227 | --------------------------------------------------------------------------------