= Yii 2 File Upload = == Example CSV File Upload == === Model === Create ''DataUploadForm'' model: 'Update existing / Insert new content', DataUploadForm::IMPORT_METHOD_UPDATE => 'Update only existing content', DataUploadForm::IMPORT_METHOD_APPEND_ALL => 'Append all content', DataUploadForm::IMPORT_METHOD_APPEND_NEW => 'Append only new content', DataUploadForm::IMPORT_METHOD_REPLACE => 'Replace content', ]; /** * @var UploadedFile */ public $dataFile; public $overwriteExistingContent = self::OVERWRITE_NO; public $importMethod = self::IMPORT_METHOD_UPDATE_INSERT; public function rules() { return [ // see '@vendor/yiisoft/yii2/validators/FileValidator.php' for all options [['dataFile'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 1, // Extensions: For CSV files, use uppercase CSV extension in actual file, otherwise it fails. 'extensions' => 'txt, CSV, xls', // MimeTypes: must match file type (extension) to be uploaded. Eg: txt, csv, png, csv (in excel). //'mimeTypes' => "text/plain, text/CSV, image/png, application/vnd.ms-excel", //'mimeTypes' => "*", // any MIME type 'checkExtensionByMimeType' => false, // false to stop verifying file extension to MIME types 'wrongExtension' => '{attribute} = [{file}]. Only these extensions are allowed: {extensions}.' ], ]; } public function upload() { if ($this->validate()) { $this->dataFile->saveAs('uploads/' . strtolower($this->dataFile->baseName) . '.' . strtolower($this->dataFile->extension) ); // save to [app]/web/uploads return true; } else { return false; } } //public function attributeLabels() //{ // return ['file' => Yii:t('app', 'Archivo')]; // es translation //} } ?> === Controller === Add these actions to your controller. Eg: ''[app]/controllers/ItemController'': namespace app\controllers; use Yii; use app\models\Item; use app\models\ItemSearch; use app\models\DataUploadForm; use yii\web\Response; use yii\web\Request; use yii\web\UploadedFile; use yii\filters\AccessControl; use yii\filters\VerbFilter; //... defined('DS') or define('DS', DIRECTORY_SEPARATOR); // set const if not defined class ItemController extends Controller { public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => [ 'index', 'create', 'view', 'update', 'delete', 'report', 'download-sample', 'batch-create', ], 'allow' => true, 'roles' => ['@'], // @ = Authenticated users ], //[ // 'allow' => true, // 'actions' => ['index', 'view'], // 'roles' => ['?'], // ? = Guest user //], ], ], //... ]; } //... /** * Creates a downloadable sample CSV file to be used in batch-create. * It return processing messages. * @return mixed */ public function actionDownloadSample($file_name = 'file.csv') { $data = [ ["code", "description", "quantity"], ["AHI-POUCH", "Audina Navy Blue Pouch", "800"], ["NOLOGO-SDELIVERYCASE", "Audina S-Delivery White Case No Logo", "96"], ]; $this->actionOutputCSV($data, $file_name); } // Usage: // actionOutputCSV(array( // array("Volvo", "BMW", "Toyota"), // array("Volvo 1", "BMW 1", "Toyota 1"), // array("Volvo 2", "BMW 2", "Toyota 2"), // array("Volvo 3", "BMW 3", "Toyota 3"), // ),'download.csv'); // Source: See more at: https://arjunphp.com/create-download-csv-files-php/#sthash.f6JCTy4J.dpuf function actionOutputCSV($data, $fileName = 'file.csv', $is_csv_excel=false) { # output headers so that the file is downloaded rather than displayed header("Content-Type: text/csv"); header("Content-Disposition: attachment; filename=$fileName"); # Disable caching - HTTP 1.1 header("Cache-Control: no-cache, no-store, must-revalidate"); # Disable caching - HTTP 1.0 header("Pragma: no-cache"); # Disable caching - Proxies header("Expires: 0"); # Start the ouput $output = fopen("php://output", "w"); if ($is_csv_excel) { fwrite($output, "sep=\t"); // set default separator to TAB, so Excel can import CSV as tab-separated } # Then loop through the rows foreach ($data as $row) { # Add the rows to the body //fputcsv($output, $row); // here you can change delimiter/enclosure fputcsv($output, $row, "\t"); // here you can change delimiter/enclosure } # Close the stream off fclose($output); } /** * Creates Item models in batch. * If create is successful, the browser will be redirected to the 'index' page. * @return mixed */ public function actionBatchCreate() { $model = new DataUploadForm(); if (Yii::$app->request->isPost) { $model->dataFile = UploadedFile::getInstance($model, 'dataFile'); $model->overwriteExistingContent = ( isset($_POST['DataUploadForm']['overwriteExistingContent']) ? $_POST['DataUploadForm']['overwriteExistingContent'] : DataUploadForm::OVERWRITE_NO ); $model->importMethod = ( isset($_POST['DataUploadForm']['importMethod']) ? $_POST['DataUploadForm']['importMethod'] : DataUploadForm::IMPORT_METHOD_APPEND ); if ($model->upload()) { // file is uploaded successfully Yii::$app->session->setFlash('success', "File {$model->dataFile} was uploaded successfully."); // clear table if ($model->overwriteExistingContent) { Item::deleteAll(); } // import data $resultsImport = $this->importDataFromCSV($model->dataFile, $model->importMethod); if ($resultsImport) { $panelCollapsed = ' === Web === Create an ''uploads'' directory in web folders. Eg: ''[app]/web/uploads'' == Example Image Upload and Save Filename in DB == === Model === In the model, override ''afterSave()'' to store image file to server, and its path in the database. Eg: ''@app/models/Organization.php'': public function afterSave($insert, $changedAttributes) { if(isset($this->logo)) { $this->logo = UploadedFile::getInstance($this, 'logo'); if(is_object($this->logo)) { $path = Yii::$app->basePath . '/images/'; // set directory path to save image $this->logo->saveAs("{$path}{$this->id}_{$this->logo}"); // saving image in folder $this->logo = "{$this->id}_{$this->logo}"; // appending id to image name \Yii::$app->db->createCommand() ->update('organization', ['logo' => $this->logo], 'id = "'.$this->id.'"') ->execute(); // manually update image name to db } } } === Controller === Add action ''actionCreate()'' to controller. Eg: ''@app/controllers/OrganizationController.php'': public function actionCreate() { $model = new Organization(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } === View === field($model, 'logo')->fileInput(['class'=>'form-control']) ?> Source: [[http://stackoverflow.com/questions/28425100/yii-2-upload-and-save-image-files-locally-and-image-url-is-saved-in-db|StackOverflow: Yii 2 Upload and Save Image Files Locally and Image URL is Saved in DB]] == Example Image File Upload == === Model === File ''@app/models/ImageFileUpload.php'': false, 'maxFiles' => 1, 'extensions' => 'png, jpg', //'mimeTypes' => "image/png, image/jpg", // must match the file type (extension) to be uploaded. Eg: png, jpg //'mimeTypes' => "*", // any MIME type 'checkExtensionByMimeType' => false, // false to stop verifying file extension to MIME types 'wrongExtension' => '{attribute} = [{file}]. Only files with these extensions are allowed: {extensions}.' ], ]; } public function upload() { if ($this->validate()) { //$this->imageFile->saveAs( // strtolower("uploads/{$this->imageFile->baseName}.{$this->imageFile->extension}") //); // save to [app]/web/uploads $this->imageFile->saveAs("uploads/" . $this->getFileName()); // save to [app]/web/uploads return true; } else { return false; } } public function getFileName() { return strtolower("{$this->imageFile->baseName}.{$this->imageFile->extension}"); } public function getFilePath() { return Yii::$app->basePath . DS . 'web' . DS . 'uploads' . DS . $this->getFileName(); } public function getFileUrl() { return Yii::$app->homeUrl . "/uploads/" . $this->getFileName(); } } ?> File ''@app/models/Tool.php'': '; */ public static function generateEmptyPng() { $image = imagecreate(PNG_DPI * LABEL_WIDTH, PNG_DPI * LABEL_HEIGHT); $canvas = imagecreate(PNG_DPI * LABEL_WIDTH, PNG_DPI * LABEL_HEIGHT); // Setup color //$color_background = imagecolorallocate($image, 255, 255, 255); // Background = white $color_background = imagecolorallocate($image, 200, 200, 200); // Background = gray $color_text = imagecolorallocate($image, 0, 0, 0); // Foreground = black // Background imagefill($image, 0, 0, $color_background); // Image border //imagerectangle($image, // LABEL_MARGIN, LABEL_MARGIN, // (LABEL_WIDTH*PNG_DPI)-LABEL_MARGIN, // (LABEL_HEIGHT*PNG_DPI)-LABEL_MARGIN, // $color_text //); // Text content imagestring($image, PNG_FONT, 20, 20, 'NO IMAGE FILE', $color_text); // Copy image to target canvas imagecopy( $canvas, // dst $image, // src 0, 0, // dst x,y 0, 0, // src x,y (LABEL_WIDTH * PNG_DPI), // src width (LABEL_HEIGHT * PNG_DPI) // src height ); imagedestroy($image); // Capture the full image from canvas ob_start(); imagepng($canvas); $imageData = ob_get_contents(); ob_end_clean(); return $imageData; } } ?> === Controller === File ''@app/controllers/ItemController.php'': //... use app\models\ImageUploadForm; defined('DS') or define('DS', DIRECTORY_SEPARATOR); class ItemController extends Controller { //... public function actionUploadImage($id) { $model = new ImageUploadForm(); $item = $this->findModel($id); if (Yii::$app->request->isPost) { $model->imageFile = \yii\web\UploadedFile::getInstance($model, 'imageFile'); if ($model->upload()) { // file is uploaded successfully Yii::$app->session->setFlash('success', "File {$model->imageFile} was uploaded successfully." ); // Assign file to item // (rename to item_code if available, otherwise keep original filename) if (!empty($item->code)) { $targetFile = "{$item->code}.{$model->imageFile->extension}"; } else { $targetFile = $model->getFileName(); } $baseWebPath = Yii::$app->basePath . DS . 'web'; //$sourcePath = $baseWebPath . DS . $model->getFileName(); $sourcePath = $model->getFilePath(); $targetDir = $baseWebPath . DS . 'img' . DS . 'data' . DS . Yii::$app->controller->id; $targetPath = $targetDir . DS . $targetFile; if (!file_exists($targetDir)) { mkdir($targetDir, 0755, true /* recursive */); } $resultsImport = move_uploaded_file($sourcePath, $targetPath); //$resultsImport = $model->imageFile->saveAs($targetPath); // save to [app]/web/img/data/item // When move_uploaded_file() fails to work, we go old school and force it to do it. if (!$resultsImport) { $resultsImport = copy($sourcePath, $targetPath); // copy source file to target unlink($sourcePath); // delete source file } $item->image_file = $targetFile; $item->save(); // import data if ($resultsImport) { Yii::$app->session->setFlash('success', "Item image {$model->imageFile} was uploaded successfully." ); } else { $msg = "Item image {$model->imageFile} failed to be moved.
"; $msg .= "- Source:{$sourcePath}
"; $msg .= "- Target:{$targetPath}"; Yii::$app->session->setFlash('error', $msg); } return $this->redirect(['view', 'id' => $id]); } else { Yii::$app->session->setFlash('error', "File {$model->imageFile} failed to be uploaded."); } } return $this->render('upload-image', [ 'model' => $model, 'item' => $item, ]); } }
=== View === File ''@app/views/item/upload-image'': title = Yii::t('app', 'Image Upload'); $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Item'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => "{$item->code} {$item->description}", 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> ['enctype' => 'multipart/form-data']]) ?>

title ?>

session->hasFlash('success')): ?> session->hasFlash('error')): ?>
field($model, 'imageFile')->fileInput(['class'=>'form-control']) ?>
File ''@app/views/item/view.php'' to call ''@app/views/item/upload-image.php'' action: image_file) ? Yii::$app->homeUrl . 'img/data/' . Yii::$app->controller->id . "/{$model->image_file}" : '' ); ?> Item Image ' . Yii::t('app', 'View Image'), [ 'class' => 'btn btn-default', 'data-toggle' => "modal", 'data-target' => "#modalImagePreview" ]) ?> ' . Yii::t('app', 'Add Image'), ['upload-image', 'id' => $model->id], ['class' => 'btn btn-default']) ?> Or simply use the Yii modal helper: image_file) ? Yii::$app->homeUrl . 'img/data/' . Yii::$app->controller->id . "/{$model->image_file}" : '' ); // Image Thumbnail if(!empty($itemImage)) { echo "Item Image"; } else { echo ""; } echo Html::a(' ' . Yii::t('app', 'Add Image'), ['upload-image', 'id' => $model->id], ['class' => 'btn btn-default'] ); // Modal Window yii\bootstrap\Modal::begin([ 'header' => '

Item Image

', 'size' => yii\bootstrap\Modal::SIZE_LARGE, 'toggleButton' => [ 'label' => ' ' . Yii::t('app', 'View Image'), 'class' => 'btn btn-default' ], ]); if(!empty($itemImage)) { echo "Item Image"; } else { echo ""; } echo ''; yii\bootstrap\Modal::end(); ?>