我想将图像上传到数据库,但图像只是存储在文件夹中而不是保存在数据库中。我不明白是什么问题,请帮助我,我在yii2新。代码在contoller上的actionUpdate中
_form.php:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\file\FileInput;
use backend\assets\DashboardAsset;
/* @var $this yii\web\View */
/* @var $model app\models\User */
/* @var $form yii\widgets\ActiveForm */
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>
Controller.php:
<?php
namespace backend\controllers;
use Yii;
use app\models\User;
use backend\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
/**
* 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 app\models;
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 \yii\db\ActiveRecord
{
/**
* @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',
];
}
}
答案 0 :(得分:0)
controller use the same code in update action also
use yii\web\UploadedFile;
use backend\models\User;
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,
]);
}
}
now add the following to your user model(not mandatory)
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png,gif,jpg', 'maxFiles' => 15],
just try the above to your code,and inform me if any error we can make it work together
答案 1 :(得分:0)
首先从模型规则的必需部分中删除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,
]);
}
}
最重要的一件事是从所需规则中删除所有其他不可见的列。否则数据永远不会保存在db。
中现在您的模型规则如下所示:
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'],
];
}
还有一件事将db中其他字段的默认值设置为NULL
或者将所有其他字段添加到表单中,以便您也可以输入值。