【发布时间】:2017-12-20 14:31:34
【问题描述】:
我想将图像上传到数据库,但图像只是存储在文件夹中而不是保存在数据库中。我不明白是什么问题,请帮助我,我是yii2的新手。代码在控制器上的 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',
];
}
}
【问题讨论】:
-
把你的动作更新或动作创建带给我你完成图像上传的地方。否则,如果你需要,我将分享我的代码,我已经完成了将图像保存到文件夹以及它是数据库表中列的路径
-
@SumithChalil 对不起,有些代码没有写,我已经编辑了控制器,请回头看。哦,谢谢你..请将链接或电子邮件发送给 ixcmuhammadramadhan@gmail.com
-
能否提供型号的代码?
-
@EdvinTenovimas 我已添加模型,请查看
标签: image file-upload upload yii2 image-upload