Files
xk-api-yii/admin/models/forms/AttachmentUploadForm.php
2024-09-19 11:32:39 +08:00

113 lines
3.5 KiB
PHP

<?php
namespace admin\models\forms;
use OSS\OssClient;
use yii\web\UploadedFile;
use function GuzzleHttp\Psr7\mimetype_from_filename;
class AttachmentUploadForm extends \yii\base\Model
{
/** @var UploadedFile */
public $file;
public $type;
public $attachment_group_id;
protected $docExt = ['txt', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv', 'pdf', 'md'];
protected $imageExt = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp',];
protected $videoExt = ['mp4', 'ogg', 'm4a','mp3'];
protected $maxSize = ['img'=>20,'video'=>100,'doc'=>5];
public function rules()
{
return [
[['file'], 'file'],
[['file'], 'validateExt'],
[['attachment_group_id'], 'integer'],
[['type'], 'string'],
];
}
public function validateExt($a, $p)
{
$supportExt = array_merge($this->docExt, $this->imageExt, $this->videoExt);
if (!in_array($this->file->extension, $supportExt)) {
$this->addError($a, '不支持的文件类型: ' . $this->file->extension);
}
if (in_array($this->file->extension, $this->imageExt)) {
if ( $this->file->size > ($this->maxSize['img'] * 1024 * 1024)) {
$this->addError($a, '图片大小超出限制,当前大小为: '
. (round($this->file->size / 1024 / 1024, 4)) . 'MB,最大限制为:'
. $this->maxSize['img'] . 'MB');
}
}
if (in_array($this->file->extension, $this->videoExt)) {
if ($this->file->size > ($this->maxSize['video'] * 1024 * 1024)) {
$this->addError($a, '视频大小超出限制,当前大小为: '
. (round($this->file->size / 1024 / 1024, 4)) . 'MB,最大限制为:'
. $this->maxSize['maxSize'] . 'MB');
}
}
}
public function checkExt($ext)
{
if (in_array($ext, $this->imageExt)) {
$type = 1;
} elseif (in_array($ext, $this->videoExt)) {
$type = 2;
} elseif (in_array($ext, $this->docExt)) {
$type = 3;
} else {
$type = 0;
}
return $type;
}
public function save()
{
if (!$this->validate()) {
return ['error'=>$this->getErrors()];
}
if ($this->type === 'image') {
$type = 1;
} elseif ($this->type === 'video') {
$type = 2;
} else {
if (in_array($this->file->extension, $this->imageExt)) {
$type = 1;
} elseif (in_array($this->file->extension, $this->videoExt)) {
$type = 2;
} elseif (in_array($this->file->extension, $this->docExt)) {
$type = 3;
} else {
$type = 0;
}
}
$mallId = \Yii::$app->mallId;
$mchId = 0;
$attachmentUpload = new AttachmentUpload([
'file' => $this->file,
'type' => $type,
'mall_id' => $mallId,
'mch_id' => $mchId,
'attachment_group_id' => $this->attachment_group_id ? $this->attachment_group_id : 0
]);
$attachment = $attachmentUpload->upload();
$attachment->thumb_url = $attachment->thumb_url ? $attachment->thumb_url : $attachment->url;
return $attachment;
}
public static function getInstanceFromFile($localFilePath)
{
return AttachmentUpload::getInstanceFromFile($localFilePath);
}
}