图像保存在文件夹中,但不保存在 Yii 2.0 的数据库中



我想将图像上传到数据库,但图像只是存储在文件夹中,而不是保存在数据库中。 我不明白问题出在哪里,请帮助我,我是 Yiii2 的新手。 代码在行动中更新控制器

_form.php :

<?php
use yiihelpersHtml;
use yiiwidgetsActiveForm;
use kartikfileFileInput;
use backendassetsDashboardAsset;
/* @var $this yiiwebView */
/* @var $model appmodelsUser */
/* @var $form yiiwidgetsActiveForm */
DashboardAsset::register($this);
?>
<div class="user-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<div class='box box-widget'>
<div class='box-header with-border'>
<h1><?= $this->title;?></h1>
</div>
<div class='box-body'>
<div class='row'>
<div class='col-sm-7'>
<div class='row'>
<div class='col-sm-3 label-div'>
First Name
</div>
<div class='col-sm-9'>
<div class='row'>
<div class='col-sm-10'>
<?= $form->field($model, 'first_name')->textInput(['maxlength' => true])->label(false) ?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class='row'>
<div class='col-sm-7'>
<div class='row'>
<div class='col-sm-3 label-div'>
Last Name
</div>
<div class='col-sm-9'>
<div class='row'>
<div class='col-sm-10'>
<?= $form->field($model, 'last_name')->textInput(['maxlength' => true])->label(false) ?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class='row'>
<div class='col-sm-7'>
<div class='row'>
<div class='col-sm-3 label-div'>
Avatar
</div>
<div class='col-sm-9'>
<div class='row'>
<div class='col-sm-10'>
<?= $form->field($model, 'file')->FileInput() ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class='box-footer'>
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>

控制器.php :

<?php
namespace backendcontrollers;
use Yii;
use appmodelsUser;
use backendmodelsUserSearch;
use yiiwebController;
use yiiwebNotFoundHttpException;
use yiifiltersVerbFilter;
use yiiwebUploadedFile;
/**
* UserController implements the CRUD actions for User model.
*/
class UserController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all User models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single User model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing User 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())) {
$path = "uploads/img/user/";
$imageName = $model->username;
//upload file
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs($path.$imageName.'.'.$model->file->extension);
$model->avatar = $path.$imageName.'.'.$model->file->extension);
$model->save()
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing User 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 User model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return User the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}

这是模型

<?php
namespace appmodels;
use Yii;
/**
* This is the model class for table "user".
*
* @property integer $id
* @property string $username
* @property string $auth_key
* @property string $password_hash
* @property string $password_reset_token
* @property string $email
* @property string $first_name
* @property string $last_name
* @property string $avatar
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
*/
class User extends yiidbActiveRecord
{
/**
* @inheritdoc
*/
public $file;
public static function tableName()
{
return 'user';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username', 'auth_key', 'password_hash', 'email', 'first_name', 'last_name', 'avatar', 'created_at', 'updated_at'], 'required'],
[['status', 'created_at', 'updated_at'], 'integer'],
[['username','file', 'password_hash', 'password_reset_token', 'email', 'first_name', 'last_name', 'avatar'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['username'], 'unique'],
[['email'], 'unique'],
[['file'],'file'],
[['password_reset_token'], 'unique'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
'email' => 'Email',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'avatar' => 'Avatar',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'file' => 'Avatar',
];
}
}

首先从模型规则的必需部分中删除avatar

第二条把这条线放$model->file->saveAs($path.$imageName.'.'.$model->file->extension);之后$model->save();

第三次检查所有语法都已更正,因为我可以看到actionUpdate缺少一个分号。

现在,您的新actionUpdate如下所示:

public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$path = "uploads/img/user/";
$imageName = $model->username;
//upload file
$model->file = UploadedFile::getInstance($model, 'file');
$model->avatar = $path.$imageName.'.'.$model->file->extension;
$model->save();
$model->file->saveAs($model->avatar);
// or   $model->file->saveAs($path.$imageName.'.'.$model->file->extension);
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}

最重要的一件事是从所需规则中删除所有其他对表单不可见的列。 否则数据永远不会保存在数据库中。

现在,模型规则如下所示:

public function rules()
{
return [
[[ 'first_name', 'last_name'], 'required'],
[['status', 'created_at', 'updated_at'], 'integer'],
[['username','file', 'password_hash', 'password_reset_token', 'email', 'first_name', 'last_name', 'avatar'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
//[['username'], 'unique'],
//  [['email'], 'unique'],
[['file'],'file'],
//  [['password_reset_token'], 'unique'],
];
}

还有一件事将数据库中其他字段的默认值设置为NULL或将所有其他字段添加到表单中,以便您也可以输入值。

控制器在更新操作中也使用相同的代码

use yiiwebUploadedFile;
use backendmodelsUser;
public function actionCreate()
{
$model = new new User();
if ($model->load(Yii::$app->request->post())){
$model->file = UploadedFile::getInstances($model, 'file');
if ($model->file) {
foreach ($model->file as $file) {
$path = 'uploads/images/' . $file->baseName . '.' . $file->extension;
$count = 0;
{
while(file_exists($path)) {
$path = 'uploads/images/' . $file->baseName . '_'.$count.'.' . $file->extension;
$count++;
}
}
$file->saveAs($path);
$files[] = $path;
} 
$model->file = implode(',', $files);
$model->save();
return $this->redirect(['view', 'id' => $model->id]);}
else{
$model->file= $model->first_name;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}

现在将以下内容添加到您的用户模型中(非强制性(

[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png,gif,jpg', 'maxFiles' => 15],

只需尝试上述代码,并通知我如果有任何错误我们可以使其协同工作