dqcj32855 2014-11-23 05:30
浏览 53
已采纳

如何在Yii中上传文件和表单数据?

I'm stuck at a problem where in I need to upload two different files (e.g. one of type jpg and the other of the type pdf/epub) along with the additional form data.

The form data should be uploaded to a database along with the path of the files and the files should be saved inside a directory.

Any help would be appreciated.

BooksController.php

<?php

     namespace backend\controllers;

     use backend\models\Books;
     use Yii;
     use yii\data\ActiveDataProvider;
     use yii\filters\VerbFilter;
     use yii\web\Controller;
     use yii\web\NotFoundHttpException;
     use yii\web\UploadedFile;

     /**
      * BooksController implements the CRUD actions for Books model.
      */
     class BooksController extends Controller
     {
         public function behaviors()
         {
             return [
                 'verbs' => [
                     'class' => VerbFilter::className(),
                     'actions' => [
                         'delete' => ['post'],
                     ],
                 ],
             ];
         }

         /**
          * Lists all Books models.
          * @return mixed
          */
         public function actionIndex()
         {
             $dataProvider = new ActiveDataProvider([
                 'query' => Books::find(),
             ]);

             return $this->render('index', [
                 'dataProvider' => $dataProvider,
             ]);
         }

         /**
          * Displays a single Books model.
          * @param integer $id
          * @return mixed
          */
         public function actionView($id)
         {
             return $this->render('view', [
                 'model' => $this->findModel($id),
             ]);
         }

         /**
          * Creates a new Books model.
          * If creation is successful, the browser will be redirected to the 'view' page.
          * @return mixed
          */
         public function actionCreate()
         {
             $model = new Books();

             $path = Yii::$app->basePath . '../../uploads/';
             if (!is_dir($path)) {
                 mkdir($path);
             }

             if (Yii::$app->request->post()) {
                 $book_file = UploadedFile::getInstance($model, 'book');
                 $cover_file = UploadedFile::getInstance($model, 'cover');

                 $book_file->saveAs($path . $book_file->baseName . '.' . $book_file->extension);
                 $cover_file->saveAs($path . $book_file->baseName . '_' . $cover_file->baseName .          '.' . $cover_file->extension);

                 return $this->redirect(['view', 'id' => $model->id]);
             }

             return $this->render('create', ['model' => $model]);
         }

         /**
          * Updates an existing Books model.
          * If update is successful, the browser will be redirected to the 'view' page.
          * @param integer $id
          * @return mixed
          */
         public function actionUpdate($id)
         {
             $model = $this->findModel($id);

             if ($model->load(Yii::$app->request->post()) && $model->save()) {
                 return $this->redirect(['view', 'id' => $model->id]);
             } else {
                 return $this->render('update', [
                     'model' => $model,
                 ]);
             }
         }

         /**
          * Deletes an existing Books model.
          * If deletion is successful, the browser will be redirected to the 'index' page.
          * @param integer $id
          * @return mixed
          */
         public function actionDelete($id)
         {
             $this->findModel($id)->delete();

             return $this->redirect(['index']);
         }

         /**
          * Finds the Books model based on its primary key value.
          * If the model is not found, a 404 HTTP exception will be thrown.
          * @param integer $id
          * @return Books the loaded model
          * @throws NotFoundHttpException if the model cannot be found
          */         
         protected function findModel($id)
         {
             if (($model = Books::findOne($id)) !== null) {
                 return $model;
             } else {
                 throw new NotFoundHttpException('The requested page does not exist.');
             }
         }
  }

Books.php (Model)

<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "books".
 *
 * @property integer $id
 * @property string $title
 * @property string $subtitle
 * @property string $description
 * @property string $author
 * @property string $isbn
 * @property integer $page
 * @property string $year
 * @property string $publisher
 * @property string $cover
 * @property string $link
 */
class Books extends \yii\db\ActiveRecord
{
    public $book;
    public $cover;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'books';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'page', 'cover', 'book'], 'required'],
            [['description'], 'string'],
            [['isbn', 'page'], 'integer'],
            ['year', 'date'],
            [['title', 'subtitle', 'author', 'publisher'], 'string', 'max' => 255],
            ['book', 'file', 'extensions' => 'pdf, epub', 'maxSize' => 1024 * 1024 * 1024],
            ['cover', 'file', 'extensions' => 'jpg, jpeg, png', 'maxSize' => 1024 * 1024 * 10]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'subtitle' => 'Subtitle',
            'description' => 'Description',
            'author' => 'Author',
            'isbn' => 'Isbn',
            'page' => 'Page',
            'year' => 'Year',
            'publisher' => 'Publisher',
            'cover' => 'Cover',
            'book' => 'Book'
        ];
    }
}

_form.php (View)

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\Books */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="books-form">

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'subtitle')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'author')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'isbn')->textInput(['maxlength' => 13]) ?>

    <?= $form->field($model, 'page')->textInput() ?>

    <?= $form->field($model, 'year')->textInput() ?>

    <?= $form->field($model, 'publisher')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'book')->fileInput() ?>

    <?= $form->field($model, 'cover')->fileInput() ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>
  • 写回答

2条回答 默认 最新

  • douneiben2240 2014-11-23 10:01
    关注

    What exactly doesn't work – saving file into filesystem, o saving model attribute? It looks like you are not calling $model->save() in your actionCreate. Also if model attribute is named file and it is used to handle uploaded file here will be a problem when saving model. Probably you want to save only file name / file path to DB. In this case you need additional attributes to handle those values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)