1. ใช้ kartik\file\FileInput; ดาวน์โหลด ติดตั้งได้ที่นี่
2. ใส่ลงใน kartik-v / yii2-widget-fileinput
3. ใส่ extensions ตรวจสอบด้วยว่าซ้ำหรือไม่
'kartik-v/yii2-widget-fileinput' => array( 'name' => 'yii2-widget-fileinput', 'version' => '1.0.6.0', 'alias' => array( '@kartik/file' => $vendorDir . '/kartik-v/yii2-widget-fileinput/src', ), ),
4. ใส่ use kartik\file\FileInput;และใส่ widget
use kartik\file\FileInput; <? = $form->field($model, 'ref')->hiddenInput()->label(false); ?> <? = $form->field($model, 'covenant')->widget(FileInput::class, [ //'options' => ['accept' => 'image/*'], 'pluginOptions' => [ 'initialPreview' => $model->initialPreview($model->covenant, 'covenant', 'file'), 'initialPreviewConfig' => $model->initialPreview($model->covenant, 'covenant', 'config'), 'allowedFileExtensions' => ['pdf', 'png', 'jpg', 'jpeg'], 'showPreview' => true, 'showCaption' => true, 'showRemove' => true, 'showUpload' => false ] ]); ?>
5.ตั้งค่าฐานข้อมูล
เพิ่ม field เช่น covenant เป็น varchar 255
แบบ uploadSigleFile
- ตั้งค่า Model
public function rules() { return [ [['covenant'], 'file', 'maxFiles' => 1, 'skipOnEmpty' => true], ]; }
ใน model function
-Controller
public function getRentalID() { $lastRental = Rental::find()->select('id')->orderBy('id DESC')->one(); $currentYear = date('Y') + 543; $currentMonth = date('m'); $newID = "00000001"; if ($lastRental) { $lastYear = substr($lastRental->id, 3, 4); $lastMonth = substr($lastRental->id, 7, 2); $lastID = (int) substr($lastRental->id, 10, 8); if ($currentYear == $lastYear && $currentMonth == $lastMonth) { $newID = str_pad($lastID + 1, 8, '0', STR_PAD_LEFT); } } return "INS{$currentYear}{$currentMonth}{$newID}"; } public function generateRenterId() { $prefix = "RT"; $remainingLength = 17 - strlen($prefix) - 4; $randomString = strtoupper(Yii::$app->security->generateRandomString($remainingLength)); $renterId = $prefix . date("Y") . $randomString; return $renterId; } //ok public function actionCreate() { $model = new Rental(); $model->id = $this->getRentalID(); $renter = new Renter(); if (!Yii::$app->user->isGuest) { $model->user_id = Yii::$app->user->identity->id; } if ($model->load(Yii::$app->request->post()) && $renter->load(Yii::$app->request->post())) { // Start a transaction for consistency $transaction = Yii::$app->db->beginTransaction(); try { $this->CreateDir(); if ($model->validate()) { $model->covenant = $this->uploadSingleFile($model); $model->docs = $this->uploadMultipleFile($model); // $model->uploadContentImage(); if ($model->save()) { $renter->id = $this->generateRenterId(); $renter->rental_id = $model->id; if ($renter->validate() && $renter->save()) { $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } } } $transaction->rollBack(); } catch (\Exception $e) { $transaction->rollBack(); Yii::error($e->getMessage(), __METHOD__); } } else { } return $this->render('create', [ 'model' => $model, 'renter' => $renter ]); } //ok private function uploadSingleFile($model, $tempFile = null) { $file = []; $json = ''; try { $UploadedFile = UploadedFile::getInstance($model, 'covenant'); if ($UploadedFile === null) { Yii::error('File upload failed. $_FILES: ' . print_r($_FILES, true), 'upload'); } if ($UploadedFile !== null) { $oldFileName = $UploadedFile->basename . '.' . $UploadedFile->extension; $newFileName = md5($UploadedFile->basename . time()) . '.' . $UploadedFile->extension; $UploadedFile->saveAs(Rental::getUploadPath() . $model->ref . '/' . $newFileName); $file[$newFileName] = $oldFileName; $json = Json::encode($file); } else { $json = $tempFile; } } catch (Exception $e) { $json = $tempFile; } return $json; } //ok public function actionDeletefile($id, $field, $fileName) { Yii::$app->response->format = Response::FORMAT_JSON; $status = ['success' => false]; if (in_array($field, ['docs', 'covenant'])) { $model = $this->findModel($id); $files = Json::decode($model->{$field}); if (is_array($files) && array_key_exists($fileName, $files)) { if ($this->deleteFile('file', $model->ref, $fileName)) { $status = ['success' => true]; unset($files[$fileName]); $model->{$field} = Json::encode($files); $model->save(); } } } return Json::encode($status); } //ok public function actionUpdate($id) { $model = Rental::findOne($id); $renter = Renter::findOne(['rental_id' => $id]); $tempCovenant = $model->covenant; if (!$model || !$renter) { throw new NotFoundHttpException('The requested page does not exist.'); } if ($model->load(Yii::$app->request->post()) && $renter->load(Yii::$app->request->post())) { $transaction = Yii::$app->db->beginTransaction(); try { if ($model->validate() && $renter->validate()) { $model->covenant = $this->uploadSingleFile($model, $tempCovenant); // $model->uploadContentImage(); if ($model->save() && $renter->save()) { $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } } $transaction->rollBack(); } catch (\Exception $e) { $transaction->rollBack(); Yii::error($e->getMessage(), __METHOD__); } } return $this->render('update', [ 'model' => $model, 'renter' => $renter ]); } public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } private function deleteFile($type = 'file', $ref, $fileName) { if (in_array($type, ['file', 'thumbnail'])) { if ($type === 'file') { $filePath = Rental::getUploadPath() . $ref . '/' . $fileName; } else { $filePath = Rental::getUploadPath() . $ref . '/thumbnail/' . $fileName; } @unlink($filePath); return true; } else { return false; } } public function actionDownload($id, $file, $file_name) { $model = $this->findModel($id); if (!empty($model->ref) && !empty($model->covenant)) { Yii::$app->response->sendFile($model->getUploadPath() . '/' . $model->ref . '/' . $file, $file_name); } else { $this->redirect(['/freelance/view', 'id' => $id]); } } private function uploadMultipleFile($model, $tempFile = null) { $files = []; $json = ''; $tempFile = Json::decode($tempFile); $UploadedFiles = UploadedFile::getInstances($model, 'docs'); if ($UploadedFiles !== null) { foreach ($UploadedFiles as $file) { try { $oldFileName = $file->basename . '.' . $file->extension; $newFileName = md5($file->basename . time()) . '.' . $file->extension; $file->saveAs(Rental::UPLOAD_MULTI_FILE_FOLDER . '/' . $model->ref . '/' . $newFileName); $files[$newFileName] = $oldFileName; } catch (Exception $e) { } } $json = json::encode(ArrayHelper::merge($tempFile, $files)); } else { $json = $tempFile; } return $json; } private function CreateDir($folderName = "") { if ($folderName != NULL) { $basePath = Rental::getUploadPath(); if (BaseFileHelper::createDirectory($basePath . $folderName, 0777)) { BaseFileHelper::createDirectory($basePath . $folderName . '/thumbnail', 0777); } } return; } private function removeUploadDir($dir) { BaseFileHelper::removeDirectory(Rental::getUploadPath() . $dir); }
แบบ uploadMultipleFile
ปัญหาและข้อควรระวัง
- การ ใส่ <div></div> เกินหรือขาด มีผลต่อการ ใช้ jquery ในการ uploadfile เพราะมีการอ้างอิง class หรือ id ที่ผิดเพี้ยนไป
- ฟิลด์ที่ทำหน้าที่รับไฟล์ จะเป็นตัวเก็บ json เพื่อเอามาใช้ในการเก็บไฟล์ path ต่างๆ เพื่อมาใช้สร้าง preview หรือลบไฟล์
ยังทำได้แค่ single file ที่พอใช้งานได้ multiple ยังไม่ได้ในโปรเจค Rental ส่วน โปรเจค test ได้
ยังทำได้แค่ single file ที่พอใช้งานได้.แต่เป็นแบบ submit form ส่วนแบบ upload ด้วย ajax ยังมีปัญหา
แบบ multiple ยังไม่ได้ในโปรเจค Rental ส่วน โปรเจค test ได้