Laravel을 사용하여 Google 구름에 파일을 업로드하는 방법

이 강좌의 목적은 이러한 임무를 완성하는 것이다
  • Prequisities

  • Create a Laravel API that creates and stores PDF locally
  • INITIALIZE PROJECT
  • USE COMPOSER PACKAGE
  • CREATE SYMBOLIC LINK
  • CREATING THE BLADE TEMPLATE FILE
  • CREATE CONTROLLER
  • ROUTING THE REQUEST
  • TESTING OUR CODE
  • SUCCESSFUL RESPONSE

  • Uploading files to Google Cloud Storage
  • CREATING THE BUCKET
  • CONFIGURATION FILES AND VARIABLES
  • USING THE GOOGLE CLOUD PACKAGE
  • Send Email Notification
  • 특권.

  • 설치 Composer
  • Google Cloud 계정 획득
  • 설치 Postman 또는 선호하는 API 테스트 도구

  • Mailtrap 계정
  • 로컬에서 PDF를 만들고 저장하는 Laravel API 만들기


    프로젝트 초기화


    먼저 새 Laravel 프로젝트를 pdf-generator 디렉토리로 초기화하려면 composer를 사용합니다.
    composer create-project laravel/laravel pdf-generator
    

    COMPOSER 패키지 사용


    저희가 사용할 composer 패키지는 laravel-dompdf입니다.프로젝트에서 이 패키지를 사용하려면 다음 명령을 사용합니다.
    composer require barryvdh/laravel-dompdf
    
    laravel-dompdf 문서:config/app.php의 providers 배열에 ServiceProvider 추가
    Barryvdh\DomPDF\ServiceProvider::class,
    
    facade를 사용하여 더 짧은 코드를 작성할 수 있습니다.이것을 정면에 추가하려면:
    'PDF' => Barryvdh\DomPDF\Facade::class,
    

    심볼 링크 만들기


    생성된 파일을 저장하기 위해서, 우리는 symbolic link을 만들어야 한다.
    Laravel 문서에서 다음을 수행합니다.

    To make these files accessible from the web, you should create a symbolic link from public/storage to storage/app/public. Utilizing this folder convention will keep your publicly accessible files in one directory that can be easily shared across deployments when using zero down-time deployment systems like Envoyer.


    심볼 링크를 만들려면 storage:link Artisan 명령을 사용합니다.
    php artisan storage:link
    
    현재, 우리는 pdf 디렉터리에 public/storage 디렉터리를 만들 것이다.여기에 생성/저장된 각 디렉토리 및 파일은 storage/app/public 디렉토리로 미러링됩니다.

    블레이드 템플릿 파일 생성


    다음 단계는 pdf 보기에 blade template file 을 만드는 것입니다.이 보기에는 사용자의 $firstname$email이라는 두 가지 값이 표시됩니다.우리는 pdfdocument.blade.php으로 명명할 것이다
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Laravel PDF demo</title>
    </head>
    <body>
      <h1>Laravel PDF demo</h1>
      <p>Firstname: {{$firstname}} </p>
      <p>Email: {{$email}} </p>
    </body>
    </html>
    

    Blade template files are created in the resources/views directory


    컨트롤러 만들기


    이 단계에서 우리는
  • laravel 프로젝트 초기화
  • laravel dompdf 패키지 생성 pdf
  • 은 생성된 pdf
  • 을 저장하기 위해 기호 링크와 폴더를 만들었습니다
  • 은 pdf
  • 용 블레이드 템플릿 파일을 만들었습니다.
    이제 모든 기능을 한데 묶을 컨트롤러를 만듭시다.
    다음 artisan 명령을 사용하여 Api 폴더에 컨트롤러를 만듭니다.
    php artisan make:controller Api/PdfGeneratorController 
    
    <?php 
    
    namespace App\Http\Controllers\Api;
    
    use Illuminate\Http\Request;
    use Illuminate\Http\JsonResponse;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\App;
    
    class PdfGeneratorController extends Controller
    {
    
        /**
         * Store a newly created resource in storage.
         *
         * @param Request $request
         * @return JsonResponse
         */
        public function store(Request $request) : JsonResponse
        {
            $validatedData = $request->validate([
                'firstname' => ['required', 'min:3', 'max:50'],
                'email' => ['required', 'email'],
            ]);
    
            $pdf = App::make('dompdf.wrapper');
            $pdf->loadView('pdfdocument', $validatedData);
            $filename = $request['firstname'] . '.pdf';
            $fileStoragePath = '/storage/pdf/' . $filename;
            $publicPath = public_path($fileStoragePath);
    
            $pdf->save($publicPath);
    
            return response()->json([
                "status" => "success",
                "message" => "PDF saved successfully ",
                "data" => [
                    "url" => url($fileStoragePath)
                ]
            ]);
    
    
        }
    
    }
    
    

    You can use the laravel-jsend package to generate JSend-compliant responses for your Laravel app


    라우팅 요청


    그 다음에 우리는 api.php 파일에 루트를 만들 것이다. 이 루트는 store()PdfGeneratorController 방법을 가리킬 것이다.

    The api.php file is located in the pdf-generator/routes directory


    다음 줄은 store 방법에만 post 요청을 할 것을 확보하고 sluggenerate-pdf이다
    Route::post('/Api/generate-pdf', [PdfGeneratorController::class, 'store']);
    

    우리 코드 테스트


    테스트의 경우 Postman 또는 선택한 API 테스트 도구를 사용합니다.우리는 store 방법에post 요청을 보낼 것이다
    [POST] http://127.0.0.1:8000/api/Api/generate-pdf
    
    Headers을 (으)로 설정
    KEY     VALUE
    Accept  application/json
    
    요청 본문을 JSON으로 보내기
    {
        "firstname" : "YourFirstName",
        "email" : "[email protected]"
    }
    

    성공적인 응답


    성공적인 응답은 JSON으로 돌아갑니다.
    {
        "status": "success",
        "message": "PDF saved successfully ",
        "data": {
            "url": "url-of-the-generated-pdf-file"
        }
    }
    

    구글 클라우드 저장소에 파일 업로드


    통 만들기


    Buckets are the basic containers that hold your data. Everything that you store in Cloud Storage must be contained in a bucket. You can use buckets to organize your data and control access to your data, but unlike directories and folders, you cannot nest buckets.


    Google Cloud Storage에서 Bucket을 만들려면 이 강좌에 따라 02:13 to 03:44으로 이동하여 서비스 계정을 만들고 05:21 to 05:31으로 이동하여 클라우드 저장소를 만들 수 있습니다.
    또는 How to create a bucket on Google Cloud에서 위 유튜브 비디오와 유사한 가이드를 볼 수 있습니다.

    구성 파일 및 변수


    생성된 json 키를 googlecloud.json으로 바꾸고 config 디렉터리로 이동/복사합니다: config/googlecloud.json.
    그런 다음 .env 파일에 다음 environment variables을 생성하여 추가합니다.
    # GOOGLE CLOUD 
    GOOGLE_CLOUD_PROJECT_ID=laravel-tutorial
    GOOGLE_CLOUD_STORAGE_BUCKET=laravel-pdf-bucket
    
    현재, 우리는 configuration file을 만들 것입니다. 이것은 .env 파일의 환경 변수에 접근할 것입니다.config 디렉토리에 파일을 생성하여 googlecloud.php으로 명명하고 다음과 같이 config/googlecloud.php에 다음 코드를 입력합니다.
    <?php
    
    return [
    
        /*
        |--------------------------------------------------------------------------
        | Google Cloud  configuration
        |--------------------------------------------------------------------------
        |
        | This file is for storing the credentials for Google Cloud 
        | 
        | 
        | 
        |
        */
    
        'project_id' => env('GOOGLE_CLOUD_PROJECT_ID'),
        'storage_bucket' => env('GOOGLE_CLOUD_STORAGE_BUCKET'),
    
    
    ];
    
    
    구성 변경 후 이 명령을 실행합니다.
    composer dump-autoload 
    php artisan config:clear
    php artisan config:cache
    

    구글 클라우드 패키지 사용


    다음 단계는 Google Cloud Storage Client for PHP을 사용하는 것입니다.
    저희가 이composer 명령으로 가방을 끌어올릴게요.
    composer require google/cloud-storage
    
    다음에 우리는 이 종류를 추가할 것이다
    use Google\Cloud\Storage\StorageClient;
    
    현재 우리는 생성된 파일을 구글 클라우드에 업로드하고 response()->json()의 구글 클라우드 저장소 URL으로 되돌려줍니다
    $googleConfigFile = file_get_contents(config_path('googlecloud.json'));
    $storage = new StorageClient([
        'keyFile' => json_decode($googleConfigFile, true)
    ]);
    $storageBucketName = config('googlecloud.storage_bucket');
    $bucket = $storage->bucket($storageBucketName);
    $fileSource = fopen($publicPath, 'r');
    $newFolderName = $request['firstname'].'_'.date("Y-m-d").'_'.date("H:i:s");
    $googleCloudStoragePath = $newFolderName.'/'.$filename;
    /* Upload a file to the bucket.
      Using Predefined ACLs to manage object permissions, you may
      upload a file and give read access to anyone with the URL.*/
    $bucket->upload($fileSource, [
      'predefinedAcl' => 'publicRead',
      'name' => $googleCloudStoragePath
    ]);
    
    return response()->json([
      "status" => "success",
      "message" => "PDF saved successfully ",
      "data" => [
          "url" => url($fileStoragePath),
          "google_storage_url" => 'https://storage.cloud.google.com/'.$storageBucketName.'/'.$googleCloudStoragePath
      ]
    ]);
    
    ext-json is missing in composer.json에서 다음과 같은 오류가 발생하면 이 문제가 해결됩니다.
    "require": {
      "ext-json": "*"
    },
    

    이메일 알림 보내기


    메일랩 등록하고 나서io 설정 아이콘 을 클릭하여 받은 편지함에서 구성 설정을 가져올 수 있습니다.

    드롭다운 목록에서 원하는 언어를 선택합니다.

    smtp 설정이 아래 목록 아래에 표시됩니다.설정을 복사하여 .env 파일에 추가합니다.
    구성 변경 후 이 명령을 실행합니다.
    composer dump-autoload 
    php artisan config:clear
    php artisan config:cache
    
    현재, 우리는 라벨의 아티산 명령을 사용하여 신화를 만들 것이다
    php artisan make:notification PdfNotification
    
    이 명령은 app/Notifications 디렉토리에 새 알림 클래스를 배치합니다.__constructor()에 다음 코드를 추가합니다.
    <?php
    /**
    * @var string
    */
    public $filePath;
    /**
    * @var string
    */
    public $fileUrl;
    
    /**
    * Create a new notification instance.
    *
    * @param string $filePath
    * @param string $fileUrl
    */
    public function __construct(string $filePath, string $fileUrl)
    {
      $this->filePath = $filePath;
      $this->fileUrl = $fileUrl;
    }
    
    toMail() 메서드에 다음 코드를 추가합니다.
    <?php
    
    /**
    * Get the mail representation of the notification.
    *
    * @param  mixed  $notifiable
    * @return MailMessage
    */
    public function toMail($notifiable): MailMessage
    {
    return (new MailMessage)
        ->subject('Laravel Notification')
        ->from('[email protected]')
        ->greeting("Dear " . $notifiable->name . ",")
        ->line("Please find attached your document")
        ->line('Thank you for using our application!')
        ->action('Download File', url($this->fileUrl))
        ->attach($this->filePath);
    }
    
    PdfGeneratorController에 다음 클래스를 추가합니다.
    use App\Models\User;
    use Illuminate\Support\Facades\Notification;
    
    다음으로 store() 메소드 내부에서 response()->json()으로 돌아가기 전에 User을 생성하여 알림을 보냅니다.
    <?php
    $user = new User([
        'email' => $request['email'],
        'name' => $request['firstname']
    ]);
    Notification::send($user, new PdfNotification($publicPath, url($fileStoragePath)));
    
    e-메일은 다음과 같아야 합니다.

    좋은 웹페이지 즐겨찾기