95 lines
2.7 KiB
PHP
95 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Traits;
|
|
|
|
use App\Repositories\MediaFileRepository;
|
|
use App\Disk;
|
|
use Auth;
|
|
use Storage;
|
|
use Str;
|
|
|
|
/**
|
|
* 使得Controller可以上傳媒體檔案
|
|
*
|
|
* Trait UploadedFileProccessable
|
|
* @package App\Traits
|
|
*/
|
|
trait UploadedFileProccessable
|
|
{
|
|
/**
|
|
* 取得上傳的媒體檔案資訊
|
|
*
|
|
* @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
|
|
* @return array
|
|
*/
|
|
private function getUpadloedFileInfo(\Symfony\Component\HttpFoundation\File\UploadedFile $file)
|
|
{
|
|
$ext = $file->getClientOriginalExtension();
|
|
$baseName = str_replace(".$ext", '', $file->getClientOriginalName());
|
|
$ext = strtolower($ext);
|
|
$alteredBaseName = Str::random(26) . time() . ".$ext";
|
|
$imageDim = getimagesize($file);
|
|
if($imageDim) {
|
|
$width = $imageDim[0];
|
|
$height = $imageDim[1];
|
|
} else {
|
|
$width = null;
|
|
$height = null;
|
|
}
|
|
$fileSize = $file->getSize();
|
|
$mimeType = $file->getMimeType();
|
|
|
|
return [
|
|
'ext' => $ext,
|
|
'fileName' => $alteredBaseName,
|
|
'fileSize' => $fileSize,
|
|
'mimeType' => $mimeType,
|
|
'width' => $width,
|
|
'height' => $height,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 上傳媒體檔案
|
|
*
|
|
* @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
|
|
* @param $diskId
|
|
* @param $userId
|
|
* @param string $path
|
|
* @param bool $isAppMedia
|
|
* @return \App\MediaFile|null
|
|
* @throws \Exception
|
|
*/
|
|
private function uploadMediaFile(\Symfony\Component\HttpFoundation\File\UploadedFile $file, $diskId, $userId, $path = null, $isAppMedia = false)
|
|
{
|
|
$fileInfo = $this->getUpadloedFileInfo($file);
|
|
|
|
$ext = $fileInfo['ext'];
|
|
$fileName = $fileInfo['fileName'];
|
|
$fileSize = $fileInfo['fileSize'];
|
|
$mimeType = $fileInfo['mimeType'];
|
|
$width = $fileInfo['width'];
|
|
$height = $fileInfo['height'];
|
|
|
|
$mediaFileRepo = app(MediaFileRepository::class);
|
|
|
|
$disk = Disk::find($diskId);
|
|
if($disk) {
|
|
$mediaFile = $mediaFileRepo->addMedia($fileName, $ext, $diskId, null, $fileSize, $mimeType, $userId, $path, $width, $height, $isAppMedia);
|
|
if($mediaFile) {
|
|
$putted = Storage::disk($disk->name)->putFileAs($path, $file, $fileName);
|
|
if($putted !== false) {
|
|
return $mediaFile;
|
|
} else {
|
|
$mediaFile->delete();
|
|
return null;
|
|
}
|
|
} else {
|
|
return null;
|
|
}
|
|
} else {
|
|
throw new \Exception('Disk not found with id: ' . $diskId);
|
|
}
|
|
}
|
|
}
|