-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathAmazonS3.php
More file actions
77 lines (69 loc) · 1.97 KB
/
AmazonS3.php
File metadata and controls
77 lines (69 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
/**
* @author: Jovani F. Alferez <vojalf@gmail.com>
*/
namespace jovanialferez\yii2s3;
/**
* A Yii2-compatible component wrapper for Aws\S3\S3Client.
* Just add this component to your configuration providing this class,
* key, secret and bucket.
*
* ~~~
* 'components' => [
* 'storage' => [
* 'class' => '\jovanialferez\yii2s3\AmazonS3',
* 'key' => 'AWS_ACCESS_KEY_ID',
* 'secret' => 'AWS_SECRET_ACCESS_KEY',
* 'bucket' => 'YOUR_BUCKET',
* ],
* ],
* ~~~
*
* You can then start using this component as:
*
* ```php
* $storage = \Yii::$app->storage;
* $url = $storage->uploadFile('/path/to/file', 'unique_file_name');
* ```
*/
class AmazonS3 extends \yii\base\Component
{
public $bucket;
public $key;
public $secret;
protected $_client;
public function init()
{
parent::init();
$this->_client = \Aws\S3\S3Client::factory([
'key' => $this->key,
'secret' => $this->secret,
]);
}
/**
* Uploads the file into S3 in that bucket.
*
* @param string $filePath Full path of the file. Can be from tmp file path.
* @param string $fileName Filename to save this file into S3. May include directories.
* @param bool $bucket Override configured bucket.
* @return bool|string The S3 generated url that is publicly-accessible.
*/
public function uploadFile($filePath, $fileName, $bucket = false)
{
if (!$bucket) {
$bucket = $this->bucket;
}
try {
$result = $this->_client->putObject([
'ACL' => 'public-read',
'Bucket' => $bucket,
'Key' => $fileName,
'SourceFile' => $filePath,
'ContentType' => \yii\helpers\FileHelper::getMimeType($filePath),
]);
return $result->get('ObjectURL');
} catch (\Exception $e) {
return false;
}
}
}