我有2列表(圖片,圖片2)我的上傳表單適用於第一個文件輸入。圖片名稱記錄到列「pic」中,並將文件上傳到服務器。我如何擴展它來上傳2個文件?幫助請2個文件上傳輸入字段在一個表單中yii2
模式
公共$ upload_file;
public function uploadFile() {
// get the uploaded file instance
$image = UploadedFile::getInstance($this, 'upload_file');
// if no image was uploaded abort the upload
if (empty($image)) {
return false;
}
$dir = Yii::getAlias('@frontend' . '/web/' . Yii::$app->params['fileUploadUrl']).$this->pic;
if (file_exists($dir)) {
unlink($dir);
}
// generate random name for the file
$this->pic = time(). '.' . $image->extension;
// the uploaded image instance
return $image;
}
public function getUploadedFile() {
// return a default image placeholder if your source avatar is not found
$pic = isset($this->pic) ? $this->pic : 'default.png';
$dir = Yii::getAlias('@frontend' . '/web/' . Yii::$app->params['fileUploadUrl']);
if (!is_dir($dir)) {
FileHelper::createDirectory($dir);
} else {
return $dir . $pic;
}
}
在控制器動作
public function actionCreate()
{
$model = new Blog();
if ($model->load(Yii::$app->request->post())) {
$upload_file = $model->uploadFile();
if ($model->validate()) {
if($model->save()) {
if ($upload_file !== false) {
$path = $model->getUploadedFile();
$upload_file->saveAs($path);
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
}
return $this->render('create', [
'model' => $model,
]);
}
視圖
<?= $form->field($model, 'upload_file')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
]); ?>
<?= $form->field($model, 'upload_file2')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
]); ?>
的問題是,我需要2個獨立fileinputs:C – Yury
稀釋在這種情況下我會建議使用Kartiks FileInput小工具 – Kyle
即時通訊使用它:)使用kartik \ file \ FileInput; – Yury