0
我有一個_form視圖進行更新和創建。有文件輸入字段,只允許zip文件。上傳zip文件時,應根據型號名稱將其解壓到一個文件夾。Yii2。爲什麼我需要上傳兩次文件才能產生效果?
問題是我必須上傳它兩次纔能有效果,因爲第一次不給我解壓縮文件夾。
這是在型號
public function upload()
{
$this->uploadedFile = UploadedFile::getInstance($this, 'filepath');
if (!empty($this->uploadedFile)) {
$slug = str_replace(' ', '-', strtolower(trim($this->name)));
$htmlPathRel = '/html/' . $slug . '/';
$htmlPathAbs = Yii::getAlias('@frontend') . '/web' . $htmlPathRel;
// delete old files before extracting
@array_map('unlink', glob($htmlPathAbs . '/*.*'));
@rmdir($htmlPathAbs);
// unpack new files
$zip = new \ZipArchive;
if ($zip->open(Yii::getAlias('@frontend') . '/web/uploads/' . $this->uploadedFile->name) === true) {
$indexHtmlContent = $zip->getFromName('index.html');
$order = new Order();
$toSearch = array_filter($order->attributes(), function($value) {
return strpos($value, 'name="billing_') !== false;
}) + array('<form');
if (!$indexHtmlContent) {
$this->addError('filepath', 'index.html not found in ' . $this->uploadedFile->name);
return false;
}
$notFound = [];
foreach ($toSearch as $string) {
if (strpos($indexHtmlContent, $string) === false) {
$notFound[] = $string;
}
}
if (!empty($notFound)) {
$this->addError('filepath', 'index.html doesn\'t contain required data: ' . implode(', ', $notFound));
return false;
}
if (!is_dir($htmlPathAbs)) {
mkdir($htmlPathAbs);
}
$zip->extractTo($htmlPathAbs);
$zip->close();
}
$this->filepath = $htmlPathRel . 'index.html';
$this->save();
if ($this->validate()) {
$this->uploadedFile->saveAs(Yii::getAlias('@frontend') . '/web/uploads/' . $this->uploadedFile->baseName . '.' . $this->uploadedFile->extension);
return true;
} else {
return false;
}
} else {
return false;
}
}
上傳功能,這是控制器創建和更新操作:
/**
* Creates a new Html model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Html();
if (Yii::$app->request->isPost) {
if ($model->load(Yii::$app->request->post())) {
Product::updateRoutes();
$model->upload();
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Html model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param string $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if (Yii::$app->request->isPost) {
$filepath = $model->filepath;
if ($model->load(Yii::$app->request->post())) {
Product::updateRoutes();
if (!$model->upload()) {
$model->filepath = $filepath;
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('update', [
'model' => $model,
]);
}
什麼是錯我的代碼?
PS:歡迎任何代碼重構的想法! :)