【发布时间】:2015-02-10 05:59:05
【问题描述】:
我在 Yii 2 中遵循了不同的文件/图像上传实现。其中之一来自 Kartik 的小部件,位于:http://demos.krajee.com/widget-details/fileinput
在我的观点中,_form.php:
<div class="col-sm-8">
<?php
// A block file picker button with custom icon and label
echo FileInput::widget([
'model' => $model,
'attribute' => 'image',
'options' => ['multiple' => true],
'pluginOptions' => [
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary btn-block',
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'browseLabel' => 'Upload Receipt'
],
'options' => ['accept' => 'image/*']
]);
?>
</div>
我只向您展示了我的一部分观点。该图像上传块伴随着其他字段,如客户姓名、日期和至、产品名称等和提交按钮。
我也已经生成了模型和控制器。
我的控制器的一部分是这样的:
public function actionCreate()
{
$model = new Invoice();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->inv_id]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}
我还没有在我的 actionCreate 中添加任何东西,因为我仍然没有任何想法。而且在 Kartik 的文件上传演示中,没有涉及或显示任何控制器。
如何将我选择上传的图片的 URL/路径保存在我的数据库中,并在本地保存该图片?
编辑:
关于@arogachev 的回答,这是我的 afterSave 在我的模型中的样子,但图像路径仍然没有保存在我的数据库中:
public function afterSave($insert, $changedAttributes)
{
if(isset($this->image)){
$this->image = UploadedFile::getInstance($this,'image');
if(is_object($this->image)){
$name = Yii::$app->basePath . 'C:\wamp3\www\basicaccounting\web\uploads'; //set directory path to save image
$this->image->saveAs($name.$this->inv_id."_".$this->image);
$this->image = $this->inv_id."_".$this->image; //appending id to image name
Yii::$app->db->createCommand()
->update('invoice', ['image' => $this->image], 'inv_id = "'.$this->inv_id.'"')
->execute(); //manually update image name to db
}
}
}
【问题讨论】:
-
你误解了我的变量
$name它只是我们存储 img 的文件夹的路径。编辑了我的答案。打印每个变量的输出,看看你在哪里出错了。