/** * @param $file string|\yii\web\UploadedFile * @param bool $preserveFileName * @param bool $overwrite * @return bool|string */ public function save($file, $preserveFileName = false, $overwrite = false) { $fileObj = File::create($file); $dirIndex = $this->getDirIndex(); if ($preserveFileName === false) { do { $filename = implode('.', [\Yii::$app->security->generateRandomString(), $fileObj->getExtension()]); $path = implode('/', [$dirIndex, $filename]); } while ($this->getFilesystem()->has($path)); } else { $filename = $fileObj->getPathInfo('filename'); $path = implode('/', [$dirIndex, $filename]); } $this->beforeSave($fileObj->getPath(), $this->getFilesystem()); $stream = fopen($fileObj->getPath(), 'r+'); if ($overwrite) { $success = $this->getFilesystem()->putStream($path, $stream); } else { $success = $this->getFilesystem()->writeStream($path, $stream); } fclose($stream); if ($success) { $this->afterSave($path, $this->getFilesystem()); return $path; } return false; }
/** * @return array * @throws \HttpException */ public function run() { $result = []; $uploadedFiles = UploadedFile::getInstancesByName($this->fileparam); foreach ($uploadedFiles as $uploadedFile) { /* @var \yii\web\UploadedFile $uploadedFile */ $output = [$this->responseNameParam => Html::encode($uploadedFile->name), $this->responseMimeTypeParam => $uploadedFile->type, $this->responseSizeParam => $uploadedFile->size, $this->responseBaseUrlParam => $this->getFileStorage()->baseUrl]; if ($uploadedFile->error === UPLOAD_ERR_OK) { $validationModel = DynamicModel::validateData(['file' => $uploadedFile], $this->validationRules); if (!$validationModel->hasErrors()) { $path = $this->getFileStorage()->save(File::create($uploadedFile)); if ($path) { $output[$this->responsePathParam] = $path; $output[$this->responseUrlParam] = $this->getFileStorage()->baseUrl . '/' . $path; $output[$this->responseDeleteUrlParam] = Url::to([$this->deleteRoute, 'path' => $path]); $paths = \Yii::$app->session->get($this->sessionKey, []); $paths[] = $path; \Yii::$app->session->set($this->sessionKey, $paths); $this->afterSave($path); } else { $output['error'] = true; $output['errors'] = []; } } else { $output['error'] = true; $output['errors'] = $validationModel->errors; } } else { $output['error'] = true; $output['errors'] = $this->resolveErrorMessage($uploadedFile->error); } $result['files'][] = $output; } return $this->multiple ? $result : array_shift($result); }