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

时间:2014-11-23 05:30:06

标签: php file-upload yii

我遇到了一个问题,我需要上传两个不同的文件(例如jpg类型和pdf / epub类型中的一个)以及其他表单数据。

表格数据应与文件路径一起上传到数据库,文件应保存在目录中。

任何帮助都将不胜感激。

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(模特)

<?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(查看)

<?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 个答案:

答案 0 :(得分:1)

究竟什么不起作用 - 将文件保存到文件系统中,o保存模型属性?您似乎没有在$model->save()中致电actionCreate。此外,如果模型属性被命名为file并且它用于处理上传文件,则在保存模型时这将是一个问题。您可能只想将文件名/文件路径保存到DB。在这种情况下,您需要其他属性来处理这些值。

答案 1 :(得分:0)

您可以使用CMultiFileUpload小部件。见example in docs。不要忘记在表单中添加multipart/form-data

$form = $this->beginWidget('CActiveForm', array(
    'id'=>'user-form',
    'htmlOptions' => array( 'enctype' => 'multipart/form-data' ),
));

文件可以与“附加表单数据一起”处理。另请参阅CUploadedFile