· 9 years ago · Oct 27, 2016, 04:22 PM
1<?php
2
3namespace App\Model;
4
5use Nette;
6use Aws\S3\S3Client;
7
8class S3Uploader
9{
10 /** @var \Aws\S3\S3Client */
11 private $s3client;
12
13 /** @var string */
14 private $bucket;
15
16 public function __construct($bucket, $accessKey, $secretKey)
17 {
18 putenv("AWS_ACCESS_KEY_ID=$accessKey");
19 putenv("AWS_SECRET_ACCESS_KEY=$secretKey");
20
21 $this->s3client = new \Aws\S3\S3Client([
22 'version' => 'latest',
23 'region' => 'us-west-2'
24 ]);
25
26 $this->bucket = $bucket;
27 }
28
29 /**
30 * Upload a file to an S3 bucket
31 *
32 * @param string $key The key used for the uploaded object
33 * @param string $file The filename to be uploaded
34 * @param string $contentType The file's content type. This defaults to "application/octet-stream"
35 *
36 * @return string A URL to access the file publically.
37 */
38 public function uploadPublic ($key, $file, $contentType = 'application/octet-stream')
39 {
40 $result = $this->s3client->putObject([
41 'Bucket' => $this->bucket,
42 'Key' => $key,
43 'SourceFile' => $file,
44 'ContentType' => $contentType,
45 'ACL' => 'public-read'
46 ]);
47
48 $url = $this->s3client->getObjectUrl($this->bucket, $key);
49
50 return $url;
51 }
52
53 public function getClient () {
54 return $this->s3client;
55 }
56
57 public function getBucket () {
58 return $this->bucket;
59 }
60}