Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/uploads/';
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'photo');
$model->filename = $image->name;
$ext = end((explode(".", $image->name)));
$model->photo = Security::generateRandomKey().".{$ext}";
$path = Yii::$app->params['uploadPath'] . $model->photo;
if($model->save()){
$image->saveAs($path);
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
我想把你的文件名插入数据库.. 此代码通过文件上传到上传文件夹但文件名未插入数据库。 所以.. 我可以改变代码吗?
答案 0 :(得分:0)
在您的模型中,请确保已声明变量“photo”
class ModelName extends \yii\db\ActiveRecord
{
public $attachment;
以及此属性的规则:
['attachment', 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png'],
在你的视图文件中
<?= $form->field($model, 'attachment')->fileInput() ?>
并在您的代码中:
$image = UploadedFile::getInstance($model, 'attachment');
$model->filename = $image->baseName;
$ext = $image->extension;
$model->photo = Security::generateRandomKey().".{$ext}";
$path = Yii::$app->params['uploadPath'] . $model->photo;
BTW:在你的代码中你有模型字段“photo”( $ model-&gt; photo = Security :: generateRandomKey()。“。{$ ext}”; )你也是将此名称用于fileinput属性名称( $ image = UploadedFile :: getInstance($ model,'photo'); )。这可能是错误的原因。