当我更新记录,即联系人时,附件(图像)会被覆盖。如何插入新附加的图像而不是覆盖旧的图像?请参阅下面的代码(我正在使用Yii 2.0 PHP框架)。
控制器
public function actionUpdate($id)
{
$session = Yii::$app->session;
$model = $this->findModel($id);
$cur_businessname = $model->business_name;
$attachment = $model->attachment;
$files = array();
if ($model->load(Yii::$app->request->post())) {
$model->attachment = UploadedFile::getInstances($model, 'attachment');
if($model->attachment) {
if (empty($model->attachment)) {
$model->attachment = UploadedFile::getInstance($model, 'attachment');
$path = 'assets/images/default.png';
$model->attachment = $path;
} else {
foreach ($model->attachment as $attachment) {
$path = 'archive/contact/'.$attachment->baseName.'.'.$attachment->extension;
$count = 0;
{
while(file_exists($path)) {
$path = 'archive/contact/'.$attachment->baseName.'_'.$count.'.'.$attachment->extension;
$count++;
}
}
$attachment->saveAs($path);
$files[] = $path;
}
$model->attachment = implode(',', $files);
}
} else {
$model->attachment = $attachment;
}
//$updatedAttachments = array_push($attachment,$path);
//var_dump($attachment);
//exit;
$model->save();
if($model->save()) {
Yii::$app->session->setFlash('success', "Success!");
} else {
Yii::$app->session->setFlash('error', "Contact Creation Failed!");
}
$model->refresh();
return $this->redirect(['index', 'id' => $session['user_id']]);
} else {
return $this->renderAjax('update', [
'model' => $model,
]);
}
}
查看
<?php
if (!empty($model->attachment)) {
$model->attachment = explode(',', $model->attachment);
$file = '';
foreach ($model->attachment as $attachment) {
$file.= Html::img(Yii::$app->urlManager->baseUrl . '/'. $attachment, ['class'=>'file-preview-image', 'alt'=>'Attachment', 'title'=>'Attachment']).',';
}
echo FileInput::widget([
'model' => $model,
'attribute' => 'attachment[]',
'options' => ['multiple' => true],
'pluginOptions' => [
'initialPreview'=>[
[$file,]
],
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary btn-block',
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'browseLabel' => 'Attach Business Card',
'maxFileCount' => 2,
'allowedFileExtensions'=>['jpg','gif','png'],
'overwriteInitial' => true,
'uploadAsync' => true,
],
'options' => ['accept' => 'image/*', 'multiple' => true]
]);
} else {
echo FileInput::widget([
'model' => $model,
'attribute' => 'imageUrl[]',
'options' => ['multiple' => true],
'pluginOptions' => [
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'maxFileCount' => 2,
'browseClass' => 'btn btn-primary btn-block',
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'browseLabel' => 'Attach Business Card',
'allowedFileExtensions'=>['jpg','gif','png'],
],
'options' => ['accept' => 'image/*', 'multiple' => true]
]);
}
?>
我尝试了array_push
,但它没有用。 $attachment
第6行的actionUpdate
包含旧附件。现在,我无法在$attachment
内使用if ($model->load(Yii::$app->request->post()))
,因为它已经在发布/提交表单之后。
如何在不覆盖旧文件的情况下插入新附加的文件?您的意见/答案将会有很大的帮助!