我使用以下内容上传图片并将其保存在服务器和数据库中。现在我想编写一个控制器来更新上传的图像。怎么办???
控制器
public function actionInvitfile()
{
$model = new Applicants();
$imgName = Yii::$app->user->identity->id;
if($model->load(Yii::$app->request->post())){
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/invitfile/' . $imgName . '.' . $model->file->extension);
$model->invitations_file='uploads/invitfile/'. $imgName . '.' . $model->file->extension;
$model->save(false);
}
return $this->goHome();
}
模型
class Applicants extends \yii\db\ActiveRecord
{
public $file;
public static function tableName()
{
return 'applicants';
}
public function rules()
{
return [
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'pdf'],
];
}
请帮助我!)
答案 0 :(得分:1)
我认为这可以起作用
public function actionUpdate($id)
{
$imgName = Yii::$app->user->identity->id;
$model = Applicants->findModel($id);
if($model->load(Yii::$app->request->post())){
unlink($model->invitations_file);
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/invitfile/' . $imgName . '.' . $model->file->extension);
$model->invitations_file='uploads/invitfile/'. $imgName . '.' . $model->file->extension;
$model->save(false);
}
return $this->goHome();
}
但是在这里你有kartij博客的官方文档,你可以在那里学到更多东西,并对你的问题有更好的答案:
http://webtips.krajee.com/advanced-upload-using-yii2-fileinput-widget/
答案 1 :(得分:0)
如果要更新单个图像,则在更新功能中,在加载后期变量之前,只需将旧图像保留在变量中即可。以下代码将为您提供帮助:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$oldImage = $model->banner;
if ($model->load(Yii::$app->request->post())) {
//get picture data and save it
$imageFile = \yii\web\UploadedFile::getInstance($model, 'banner');
if($imageFile) {
unlink(Yii::getAlias('@app').'/../../uploads/banners/' . $oldImage);
$fileName = $imageFile->baseName.'_'.time().'.'.$imageFile->extension;
$imageFile->saveAs(Yii::getAlias('@app').'/../../uploads/banners/' . $fileName);
$model->banner = $fileName;
$model->save();
} else {
$model->banner = $oldImage;
$model->save(false);
}
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}