파일스토리지 (파일조작)

- 파일업로드

  1. config/filesystems.php파일에 파일스토리지 관련 설정이 들어있다

  2. public_path('storage'): 공개 디렉토리, Laravel 프로젝트의 public 디렉토리 내에 위치합니다.

    실제 웹 브라우저에서 접근 가능한 공개적인 파일들이 이 디렉토리에 저장됩니다.

  3. storage_path('app/public'): 비공개 디렉토리, Laravel 프로젝트의 storage 디렉토리 내에 위치합니다.

    사용자가 업로드한 파일과 같은 비공개적인 파일들이 이 디렉토리에 저장됩니다.

  4. 위의 두 디렉토리를 심볼릭 링크로 연결하는 명령어는 php artisan storage:link입니다.

    이 명령어를 실행하면 public/storage 디렉토리가 생성되며, 해당 디렉토리가 storage/app/public 디렉토리와 심볼릭 링크로 연결됩니다.

  5. 위의 명령어를 입력하면, 비공개 디렉토리에 생성된 파일들에 대해 심볼릭 링크가 생성된 public/storage 디렉토리 내에 심볼릭 파일로 생성됩니다.

    이렇게 함으로써, 비공개 디렉토리에 저장된 파일들을 웹 브라우저에서 직접 접근할 수 있게 됩니다. 실제 파일들은 여전히 storage/app/public에 존재하며, 웹 서버를 통해 public/storage에 접근할 경우 심볼릭 링크를 통해 해당 파일들에 접근합니다.

  6. 심볼릭 링크로 연결한 설정은 config/filesystems.php 파일의 'links' => [public_path('storage') => storage_path('app/public')] 배열에 등록됩니다.

    이렇게 등록된 설정은 심볼릭 링크의 생성과 관련된 Laravel 파일 시스템 설정입니다.

  7. echo asset('storage/file.txt')를 사용하면 Laravel에서 웹 브라우저에서 접근 가능한 URL을 생성하는 함수입니다.

    이 함수를 사용하여 파일의 URL을 생성하면 해당 파일을 웹 브라우저에서 볼 수 있게 됩니다.

    즉 public/storage/file.txt 파일의 URL을 반환하게 됩니다. ( = storage/app/public/file.txt을 반환하는것과 같다)

파일의 인스턴스 사용

파일 저장

$request->file('avatar')->store('avatars');

$path = $request->file('avatar')->storeAs( 'avatars', $request->user()->id ); // 파일명지정

$path = $request->file('avatar')->storeAs( 'avatars', $request->user()->id, 's3' ); // 파일명을 지정하며 어느디스크에 저장할지 지정함(s3디스크)

파일정보조회

$file = $request->file('avatar');

$name = $file->hashName(); // 파일명취득

$extension = $file->extension(); // 파일타입취득


- Storage파사드 사용

  1. filesystems.php에 설정된 파일드라이버(local, s3, ftp)를 아래의 Storage퍼사드에서 루트로 사용함

    'default' => env('FILESYSTEM_DISK', 'local'),를 사용하는 경우

    설정된 값은 'root' => storage_path('app') 이다

  2. 비공개 디렉토리의 내용을 외부에 보여줄수있음

  3. 파일드라이버가 (local, s3, ftp)이기때문에 유연하게 사용가능

  4. 파일다운로드,업로드,저장,삭제,조회,이동,파일메타데이터조회 등의 파일조작을 쉽게 사용가능하게함

파일조회

Storage::get('file.jpg');

storage/app/file.jpg 파일을 조회

파일 다운로드

Storage::download('file.jpg');

storage/app/file.jpg파일을 다운로드할수있는 url을 response로 반환

파일 URL

$url = Storage::url('file.jpg');

/storage/file.jpg라는 url을 반환한다. (심볼릭링크 등록[php artisan storage:link]이 되어야 실제로 url에 의한 이미지를 볼수있다)

파일 저장

Storage::put('file.jpg', $contents);

파일 복사/이동

Storage::copy('old/file.jpg', 'new/file.jpg');

Storage::move('old/file.jpg', 'new/file.jpg');

파일의 URL생성시 asset()과 url()의 차이

asset('storage/file.jpg') // 완전한 url을 생성함

"http://127.0.0.1:8000/storage/file.jpg"

Storage::url('file.jpg') // 부분적인 url을 생성함

(심볼릭링크가 생성되어서 public/storage폴더가 있다는 가정하에 /storage가 붙어서 출력된다)

"/storage/file.jpg"


참조

https://laravel.kr/docs/9.x/filesystem#the-local-driver

Jul 27, 2023 Views 95