migrasi upload file ke s3 amazon

This commit is contained in:
Server D3 Linksehat
2025-08-25 09:14:11 +07:00
parent df02dc0c5f
commit ba2490147f
8 changed files with 167 additions and 34 deletions

View File

@@ -18,16 +18,18 @@ class File extends Model
'name',
'original_name',
'extension',
'source',
'path',
'created_by',
'updated_by',
'deleted_at',
'reason'
];
protected $hidden = [
'created_at',
'updated_at',
'deleted_at',
// 'deleted_at',
'created_by',
'updated_by',
'deleted_by',
@@ -78,20 +80,64 @@ class File extends Model
public function getUrlAttribute()
{
return url(Storage::url($this->path));
// Jika path kosong, kembalikan null
if (!$this->path) {
return null;
}
// Cek nilai 'source'. Jika 's3', gunakan disk S3.
// Selain itu (termasuk null atau 'local'), gunakan disk 'public'.
if ($this->source === 's3') {
try {
return Storage::disk('s3')->temporaryUrl(
$this->path,
now()->addMinutes(60) // expired 1 jam
);
} catch (\Exception $e) {
return Storage::disk('s3')->url($this->path); // fallback kalau public
}
}
return Storage::disk('public')->url($this->path);
}
// public static function storeFile($type, $id, $file)
// {
// // $fileName = self::getFileName($type, $id);
// $fileName = $file->getClientOriginalName();
// $directory = self::getDirectory($type);
// $extension = $file->getClientOriginalExtension();
// $path = $directory . $fileName . '.' . $extension;
// $file->storeAs('public/' . $directory, $fileName);
// return $path;
// }
public static function storeFile($type, $id, $file)
{
// $fileName = self::getFileName($type, $id);
$fileName = $file->getClientOriginalName();
$directory = self::getDirectory($type);
// Pastikan directory tidak punya trailing slash
$directory = rtrim(self::getDirectory($type), '/');
// Buat nama file yang unik dan aman
$originalName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$path = $directory . $fileName . '.' . $extension;
$file->storeAs('public/' . $directory, $fileName . '.' . $extension);
return $path;
$safeName = Str::slug($originalName);
$uniqueName = $safeName . '-' . uniqid() . '.' . $extension;
// Upload file ke disk 's3' dengan visibility 'public'
$path = Storage::disk('s3')->putFileAs(
$directory,
$file,
$uniqueName,
'public'
);
// Kembalikan path dan nama unik agar bisa digunakan di controller
return [
'path' => $directory . '/' . $uniqueName, // hasil konsisten
'name' => $uniqueName,
];
}
public static function storeFileChat($type, $id, $file)
{
// $fileName = self::getFileName($type, $id);