IT박스

Laravel 5-View 내 저장소에 업로드 된 이미지에 액세스하는 방법

itboxs 2020. 6. 10. 22:53
반응형

Laravel 5-View 내 저장소에 업로드 된 이미지에 액세스하는 방법


라 라벨 스토리지에 사용자의 아바타를 업로드했습니다. 액세스하여 뷰에서 렌더링하려면 어떻게해야합니까?

서버가 모든 요청을 가리키고 /public있으므로 /storage폴더 에있는 경우 어떻게 표시 할 수 있습니까?


가장 좋은 방법은 만드는 것입니다 기호 링크가 잘 지적 @SlateEntropy 같은 아래의 대답을 . 이를 위해 Laravel 버전 5.3부터이 작업을 매우 쉽게 수행 할 수 있는 명령포함합니다 .

php artisan storage:link

그것은 당신 public/storagestorage/app/public위해 심볼릭 링크를 만들고 그것이 전부입니다. 이제 다음 /storage/app/public과 같은 링크를 통해 모든 파일에 액세스 할 수 있습니다.

http://somedomain.com/storage/image.jpg

어떤 이유로 든 공유 링크 등에서 심볼릭 링크를 만들 수 없거나 일부 액세스 제어 논리 뒤의 일부 파일을 보호하려는 경우 다음과 같은 특수 경로를 사용할 수 있습니다. 이미지를 제공합니다. 예를 들어 다음과 같은 간단한 폐쇄 경로 :

Route::get('storage/{filename}', function ($filename)
{
    $path = storage_path('public/' . $filename);

    if (!File::exists($path)) {
        abort(404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

심볼릭 링크가있는 것처럼 파일에 액세스 할 수 있습니다.

http://somedomain.com/storage/image.jpg

당신이 사용하는 경우 개입 이미지 라이브러리 당신은 그것의 내장 사용할 수있는 response메이크업 물건을 더 간결에 방법 :

Route::get('storage/{filename}', function ($filename)
{
    return Image::make(storage_path('public/' . $filename))->response();
});

경고

파일을 수동으로 제공 하면 파일 내용을 읽고 보내기 위해 전체 라 라벨 요청 수명주기를 거치 므로 HTTP 서버가 처리하는 것보다 상당히 느리기 때문에 성능 저하 가 발생 한다는 점에 유의하십시오 .


하나의 옵션은 스토리지 디렉토리의 하위 폴더와 공용 디렉토리 사이에 기호 링크를 작성하는 것입니다.

예를 들어

ln -s /path/to/laravel/storage/avatars /path/to/laravel/public/avatars

이것은 Laravel 의 개발자 인 Taylor Otwell이 구축 한 배포 관리자 인 Envoyer 에서 사용하는 방법이기도합니다 .


Laravel 5.2 문서에 따르면 공개적으로 액세스 할 수있는 파일은 디렉토리에 저장해야합니다

storage/app/public

웹에서 그들에 액세스 할 수 있도록하려면에서 심볼릭 링크 생성해야 public/storage하는가 storage/app/public.

ln -s /path/to/laravel/storage/app/public /path/to/laravel/public/storage

이제 자산 도우미를 사용하여보기에서 파일에 대한 URL을 만들 수 있습니다.

echo asset('storage/file.txt');

Windows에있는 경우 cmd에서이 명령을 실행할 수 있습니다.

mklink /j /path/to/laravel/public/avatars /path/to/laravel/storage/avatars 

에서 : http://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html


우선 artisan 명령을 사용하여 스토리지 디렉토리에 대한 기호 링크를 작성해야합니다.

php artisan storage:link

그런 다음 모든보기에서 이와 같은 URL 도우미를 통해 이미지에 액세스 할 수 있습니다.

url('storage/avatars/image.png');

모든 개인 이미지와 문서를 저장 디렉토리에 저장하는 것이 좋습니다. 그러면 특정 유형의 사용자가 파일에 액세스하거나 제한 할 수있는 파일 에테르를 완전히 제어 할 수 있습니다.

경로 / 문서를 만들고 컨트롤러 방법을 가리 킵니다 :

public function docs() {

    //custom logic

    //check if user is logged in or user have permission to download this file etc

    return response()->download(
        storage_path('app/users/documents/4YPa0bl0L01ey2jO2CTVzlfuBcrNyHE2TV8xakPk.png'), 
        'filename.png',
        ['Content-Type' => 'image/png']
    );
}

적중하면 localhost:8000/docs파일이 있으면 다운로드됩니다.

파일은 root/storage/app/users/documents위 코드에 따라 디렉토리에 있어야합니다.이 파일은에서 테스트되었습니다 Laravel 5.4.


If you are using php then just please use the php symlink function, like following:

symlink('/home/username/projectname/storage/app/public', '/home/username/public_html/storage')

change the username and project name to the right names.


If you want to load a small number of Private images You can encode the images to base64 and echo them into <img src="{{$image_data}}"> directly:

$path = image.png
$full_path = Storage::path($path);
$base64 = base64_encode(Storage::get($path));
$image_data = 'data:'.mime_content_type($full_path) . ';base64,' . $base64;

I mentioned private because you should only use these methods if you do not want to store images publicly accessible through url ,instead you Must always use the standard way (link storage/public folder and serve images with HTTP server).

Beware encoding to base64() have two important down sides:

  1. This will increase image size by ~30%.
  2. You combine all of the images sizes in one request, instead of loading them in parallel, this should not be a problem for some small thumbnails but for many images avoid using this method.

without site name

{{Storage::url($photoLink)}}

if you want to add site name to it example to append on api JSON felids

 public function getPhotoFullLinkAttribute()
{
    return env('APP_URL', false).Storage::url($this->attributes['avatar']) ;
}

If you are like me and you somehow have full file paths (I did some glob() pattern matching on required photos so I do pretty much end up with full file paths), and your storage setup is well linked (i.e. such that your paths have the string storage/app/public/), then you can use my little dirty hack below :p)

 public static function hackoutFileFromStorageFolder($fullfilePath) {
        if (strpos($fullfilePath, 'storage/app/public/')) {
           $fileParts = explode('storage/app/public/', $fullfilePath);
           if( count($fileParts) > 1){
               return $fileParts[1];
           }
        }

        return '';
    }

참고URL : https://stackoverflow.com/questions/30191330/laravel-5-how-to-access-image-uploaded-in-storage-within-view

반응형