91 lines
2.4 KiB
PHP
91 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Traits;
|
|
|
|
use Illuminate\Http\File;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Arr;
|
|
use Illuminate\Support\Facades\App;
|
|
use Illuminate\Support\Str;
|
|
|
|
trait AudioFileHelper
|
|
{
|
|
use MimeToExtensionHelper;
|
|
|
|
public $public_path = "/public/uploads/";
|
|
public $storage_path = "/storage/uploads/";
|
|
|
|
public function uploadAudioFile($file, $prefix, bool $isEncoded): string
|
|
{
|
|
if ($isEncoded) {
|
|
$file = $this->create_audio_file_from_base64($file);
|
|
}
|
|
$audioPath = '';
|
|
if ($file) {
|
|
$extension = $file->getClientOriginalExtension();
|
|
$fileName = $prefix . '_' . Str::random(30) . '.' . $extension;
|
|
$url = $file->storeAs($this->public_path, $fileName);
|
|
$publicPath = public_path($this->storage_path . $fileName);
|
|
|
|
|
|
$audioPath = preg_replace("/public/", "", $url);
|
|
}
|
|
return $audioPath;
|
|
}
|
|
|
|
public function create_audio_file_from_base64($base64File): UploadedFile
|
|
{
|
|
$fileData = base64_decode(Arr::last(explode(',', $base64File)));
|
|
|
|
//Get MimeType
|
|
$fileInfo = finfo_open();
|
|
$mimeType = finfo_buffer($fileInfo, $fileData, FILEINFO_MIME_TYPE);
|
|
|
|
//Get Extension from MimeType
|
|
$ext = $this->mime2ext($mimeType);
|
|
|
|
// save it to temporary dir first.
|
|
$tempFilePath = sys_get_temp_dir() . '/' . Str::uuid()->toString() . '.' . $ext;
|
|
|
|
file_put_contents($tempFilePath, $fileData);
|
|
|
|
$tempFileObject = new File($tempFilePath);
|
|
return new UploadedFile(
|
|
$tempFileObject->getPathname(),
|
|
$tempFileObject->getFilename(),
|
|
$tempFileObject->getMimeType(),
|
|
0,
|
|
true
|
|
);
|
|
}
|
|
|
|
public function getAudioFileFullUrl($file): null|string
|
|
{
|
|
if ($file) {
|
|
return App::make('url')->to('/') . '/storage' . $file;
|
|
}
|
|
return NULL;
|
|
|
|
}
|
|
|
|
public function updateAudioFile($file, $existingFile, $prefix, bool $isEncoded): bool|string
|
|
{
|
|
$isDeleted = $this->deleteAudioFile($existingFile);
|
|
if ($isDeleted) {
|
|
return $this->uploadAudioFile($file, $prefix, $isEncoded);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public function deleteAudioFile($file): bool
|
|
{
|
|
$file = 'storage' . $file;
|
|
if (file_exists($file)) {
|
|
unlink($file);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
}
|