munak

Laravel 5 이미지 저장하기 본문

SW 개발 언어/7. Laravel 5

Laravel 5 이미지 저장하기

moonhak 2016. 3. 15. 21:58

이미지 저장하는 방법

1. view에서 input 태그의 name을 지정한다. 저는 'image'로 지정했습니다.

<input type="file" id="image" accept="image/*" name="image"

2. name으로 넘겨받은 image file을 controller 에서 변수로 받습니다.

$images = Input::file('image');

3. 이미지 저장 위치를 지정하고, 저장할 이름을 정합니다.

$image_name = str_random(6)."-".$images->getClientoriginalName();
$destinationPath = base_path().sprintf("/docs/uploads", $image_name);

여기서 에러가 많이 발생합니다.

저는 파일 이름을 랜덤한 문자 6개 + '-' + 원래 파일명 으로 지정했습니다. (ex : abcdef-filename.png)

파일 경로는 base_path() 매소드가 laravel이 설치된 기본 경로를 나타내주기 때문에 + /docs/uploads 폴더에 저장했습니다.

public_path()를 사용하면 기본경로/public/으로 설정됩니다.

추가로 /docs/uploads/%s 를 생성하면, 파일명과 동일한 이름의 폴더를 생성하고, 그 안에 이미지 파일을 저장합니다.

4. 이미지 파일을 저장합니다.

$images->move($destinationPath, $image_name);

move 메소드를 사용하고, 매개변수는 저장위치, 파일명 순입니다.





Comments