[Laravel] 파일업로드 처리하기

[Laravel] 파일업로드 처리하기 updated_at: 2024-02-06 16:53

파일업로드 처리하기

스토리지 관련 참조

파일명이 URL로 주어진 경우

$contents = file_get_contents($avatar);
Storage::put('save_path', $contents);

멀티 파일일 경우

  • html
<input type='file' name='uploads[0]'>
<input type='file' name='uploads[1]'>
.....
if(is_array($request->file('uploads')))
  foreach ($request->file('uploads') as $index => $upload) {
    if ($upload == null) continue;

    //get file path
    //upload to storage
    $filename = $upload->getClientOriginalName(); // 파일명
    $fileextension = $upload->getClientOriginalExtension(); // 확자장명

    $path = Storage::put($filepath, $upload); // 파일 저장경로
    basename($path); // disk 상의 경로
  }//foreach if
}

단일 파일일 경우

위에서 사용한 Storage::put 도 좋지만 아래 것이 더욱 간단하고 저장될 파일명도 쉽게 변경할 수 있다.

$path = $request->file('avatar')->store('avatars'); // 그대로 저장할 경우
$request->file('avatar')->storeAs('public/avatars', $user->id); // 이름을 변경하여 저장할 경우 (경로, 파일명)
$path = Storage::putFileAs('avatars', $request->file('avatar'), $request->user()->id); // 경로명, 파일, 파일명
평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글