2024-02-13 20:44:01 +08:00
|
|
|
<?php
|
|
|
|
/*
|
|
|
|
* 这里的代码借鉴了 https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload
|
|
|
|
*/
|
|
|
|
|
|
|
|
namespace app\models;
|
|
|
|
|
2024-03-10 13:20:32 +08:00
|
|
|
use app\utils\FileSizeHelper;
|
2024-02-13 20:44:01 +08:00
|
|
|
use Yii;
|
|
|
|
use yii\base\Model;
|
|
|
|
use yii\web\UploadedFile;
|
|
|
|
|
|
|
|
class UploadForm extends Model
|
|
|
|
{
|
|
|
|
public UploadedFile|null $uploadFile;
|
|
|
|
public $targetDir; //相对路径
|
|
|
|
|
2024-03-10 13:20:32 +08:00
|
|
|
public function rules(): array
|
2024-02-13 20:44:01 +08:00
|
|
|
{
|
|
|
|
return [
|
|
|
|
[['uploadFile'], 'file', 'skipOnEmpty' => false, 'checkExtensionByMimeType' => false], //这规则奇怪的放走近科学都可以拍好几集了
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2024-03-10 16:37:22 +08:00
|
|
|
public function upload(int $is_vault_file = 0): bool
|
2024-02-13 20:44:01 +08:00
|
|
|
{
|
|
|
|
if ($this->validate()) {
|
|
|
|
if ($this->targetDir === null) {
|
|
|
|
$this->targetDir = '.';
|
|
|
|
}
|
|
|
|
if (str_contains($this->targetDir, '..')) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
$userHomeDir = Yii::getAlias(Yii::$app->params['dataDirectory']) . '/' . Yii::$app->user->id;
|
2024-03-10 16:37:22 +08:00
|
|
|
if ($is_vault_file == 1) {
|
|
|
|
$userHomeDir .= '.secret';
|
|
|
|
}
|
2024-02-13 20:44:01 +08:00
|
|
|
$absolutePath = $userHomeDir . '/' . $this->targetDir;
|
|
|
|
if (!is_dir($absolutePath)) {
|
|
|
|
return false;
|
|
|
|
}
|
2024-02-14 19:12:09 +08:00
|
|
|
$fileName = $this->uploadFile->fullPath;
|
|
|
|
$directory = dirname($absolutePath . '/' . $fileName);
|
|
|
|
if (!is_dir($directory)) {
|
|
|
|
mkdir($directory, 0777, true);
|
2024-02-13 20:44:01 +08:00
|
|
|
}
|
2024-03-10 13:20:32 +08:00
|
|
|
if (!FileSizeHelper::hasEnoughSpace($this->uploadFile->size)) {
|
|
|
|
return false;
|
|
|
|
}
|
2024-02-13 20:44:01 +08:00
|
|
|
$this->uploadFile->saveAs($absolutePath . '/' . $fileName);
|
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|