[ Model ]
backend/models/Import.php
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
/**
* ContactForm is the model behind the contact form.
*/
class Import extends Model
{
public $file;
public function rules()
{
return [
[['file'], 'file'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'file' => 'ไฟล์นำเข้า (CSV จาก excel)',
];
}
/**
* Sends an email to the specified email address using the information collected by this model.
*
* @param string $email the target email address
* @return boolean whether the email was sent
*/
}
[ Controller ]
backend/controllers/SiteController.php
เรียกใช้งานโดย index.php?r=site/import
<?php
use yii\web\UploadedFile;
use backend\models\Import;
// เนื้อหาบางส่วนในไฟล์
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index','import'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actionImport()
{
$model = new Import();
$filename='';
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->validate()) {
$model->file->saveAs('import/import.'.$model->file->extension);
$filename=$_FILES['Import']['name']['file'];
//echo phpinfo();
}
}
return $this->render('import', ['model' => $model,'filename'=>$filename]);
}
[ View ]
backend/views/site/import.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use backend\models\Import;
/* @var $this yii\web\View */
/* @var $model app\models\Simcard */
/* @var $form yii\widgets\ActiveForm */
?>
<?php
$model=new Import();
if (!empty($filename))
{
?>
<div class="jumbotron">
<h1>ได้รับไฟล์ข้อมูลแล้ว</h1>
<p class="lead">โปรดตรวจสอบเนื้อหาอีกครั้ง เพื่อเช็คความเรียบร้อย</p>
<p><a class="btn btn-lg btn-success" href="index.php">กลับสู่หน้าแรก</a></p>
<h2><?=$filename; ?></h2>
<?php if (($_FILES["Import"]["type"]["file"]=="image/jpeg")||
($_FILES["Import"]["type"]["file"]=="image/gif")||
($_FILES["Import"]["type"]["file"]=="image/png"))
echo "<img src=upload/".$filename.">"; ?>
<?php if ($_FILES["Import"]["type"]["file"]=="text/comma-separated-values")
echo "<h1>CSV</h1>";
?>
</div>
<?php
//echo phpinfo();
}
else
{
?>
<div class="upload-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton( 'ส่งข้อมูล', ['class' =>'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
}
?>