简体   繁体   中英

Laravel 8 Download file from AWS S3 Buckets

I have tried a few different methods from various Stackoverflow and I am kinda stumped.

I am trying to return a presigned url so that I can display it to the end user for them to download requested file.

My Code

    $this->setDestination($documents->location); // folder/path/to/file
    $this->setFileName($documents->name); // filename.pdf, filename.doc, etc

    $client = Storage::disk('s3')->getDriver()->getAdapter()->getClient();
    $bucket = Config::get('filesystems.disks.s3.bucket');

    $command = $client->getCommand('GetObject', [
        'Bucket' => $bucket,
        'Key' => 'docs/c1e09c74-fe9a-4bd8-b624-99249e7d4f98/123456/123456-1/209999/Document/3c0e772b-97cb-4e2e-bc33-fdbfae6a4adc.pdf'
        /*
        'Key' => $this->getDestination() . $this->getFileName()
         */
    ]);

    $request = $client->createPresignedRequest($command, '+20 minutes');

    // Get the actual presigned-url
    $presignedUrl = (string)$request->getUri();

It will return a URL as such

https://MYSECRET.s3.us-west-2.amazonaws.com/docs/c1e09c74-fe9a-4bd8-b624-99249e7d4f98/123456/123456-1/209999/Document/3c0e772b-97cb-4e2e-bc33-fdbfae6a4adc.pdf3c0e772b-97cb-4e2e-bc33-fdbfae6a4adc.pdf?X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAZCGODPV3AFHI2YM4%2F20201128%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20201128T051428Z&X-Amz-SignedHeaders=host&X-Amz-Expires=1200&X-Amz-Signature=0232040d7d9c46a51ee6c9424eec52151f6adc48191357d5022094603cbc58e5

When I visit the URL it will display the following.

NoSuchKeyThe specified key does not exist.docs/c1e09c74-fe9a-4bd8-b624-99249e7d4f98/123456/123456-1/209999/Document/3c0e772b-97cb-4e2e-bc33-fdbfae6a4adc.pdf3c0e772b-97cb-4e2e-bc33-fdbfae6a4adc.pdf9739CAE34DDF00A89ysmJVtjo8oZ1eckvRAW5autyeRLjjhhHc+xZEdStC2iEthhnRBSZHMBYorOt3RKLaZ/yiCMKOo=

When I view it on the S3 Bucket console I will have the

The Key is showing

docs/c1e09c74-fe9a-4bd8-b624-99249e7d4f98/123456/123456-1/209999/Document/3c0e772b-97cb-4e2e-bc33-fdbfae6a4adc.pdf

Object Url as defined

https://MYSECRET.s3-us-west-2.amazonaws.com/docs/c1e09c74-fe9a-4bd8-b624-99249e7d4f98/123456/123456-1/209999/Document/3c0e772b-97cb-4e2e-bc33-fdbfae6a4adc.pdf

What am I missing?

//$filename is file name
Route::get('/user/{$filename}', [UserController::class, 'index']);
public function filedownload($filename){
 $headers = ['Content-Type'        => 'application/jpeg','Content- 
 Disposition' =>'attachment; filename=one.png',];
 return \Response::make(Storage::disk('s3')->get('foldername/'.$keyid), 
 200,$headers);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM