当我尝试使文件上传多次失败时。当我处理上传时,结果是错误的。错误描述可以看到下面的内容。以及解决方案如何?
控制器中的未知属性 - yii \ base \ UnknownPropertyException。 获取未知属性:app \ models \ Gallery :: Batas KRS.JPG
代码
public function actionGallery()
{
$model = new \app\models\Gallery();
if (\Yii::$app->request->post()) {
$model->image = \yii\web\UploadedFile::getInstances($model, 'image');
if ($model->validate()) {
foreach ($model->image as $file) {
$saveTo = 'uploads/' . $file->baseName . '.' . $model->$file->extension;
if ($file->saveAs($saveTo)) {
$model2 = new \app\models\Gallery(['image' => $file->baseName . '.' . $file->extension,
]);
$model2->save(false);
}
}
\Yii::$app->session->setFlash('success', 'Success uploaded !');
}
}
return $this->render('gallery', ['model' => $model
]);
}
视野中的代码
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>
<h1>Gallery</h1>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'] ]) ?>
<?= $form->field($model, 'image[]')->fileInput(['multiple' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php
ActiveForm::end();
?>
模型中的代码
<?php
namespace app\models;
use Yii;
use yii\web\UploadedFile;
use yii\validators\FileValidator;
/**
* This is the model class for table "gallery".
*
* @property integer $id
* @property string $image
*/
class Gallery extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'gallery';
}
/**
* @inheritdoc
*/
public function rules()
{
return
[[['image'], 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxFiles' => 0], ]
;
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'image' => 'Image',
];
}
}
答案 0 :(得分:0)
我还没有看到这种保存方法!
if ($file->saveAs($saveTo)) { $model2 = new \app\models\Gallery(['image' => $file->baseName . '.' . $file->extension, ]); $model2->save(false); }
您的代码应如下所示:
if ($file->saveAs($saveTo)) {
$model2 = new \app\models\Gallery();
$model2->isNewRecord = true;
$model2->image = $file->baseName . '.' . $file->extension;
$model2->save(false);
}