nativegallery/app/Services/Upload.php

82 lines
2.3 KiB
PHP
Raw Normal View History

2024-07-05 07:26:39 +03:00
<?php
namespace App\Services;
class Upload
{
2024-07-05 09:49:49 +03:00
public $type;
public $src;
public $size;
public $name;
2024-07-05 07:26:39 +03:00
private static function human_filesize($bytes, $dec = 2): string
{
$size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$factor = floor((strlen($bytes) - 1) / 3);
if ($factor == 0)
$dec = 0;
return sprintf("%.{$dec}f %s", $bytes / (1024 ** $factor), $size[$factor]);
}
public function __construct($file, $location)
{
2024-07-21 02:59:40 +03:00
if (is_array($file)) {
$tmpname = $file['tmp_name'];
$type = explode('/', $file['type'])[0];
$name = $file['name'];
$fileext = pathinfo($file['name']);
} else {
$tmpname = $file;
$type = filetype($file);
$name = basename($file);
$fileext = pathinfo($file, PATHINFO_EXTENSION);
}
2024-07-10 12:30:10 +03:00
$cstrong = True;
2024-07-21 02:59:40 +03:00
$filecdn = bin2hex(openssl_random_pseudo_bytes(64, $cstrong)) . '.' . $fileext;
2024-07-05 07:26:39 +03:00
$folder = $location . $filecdn;
$s3 = new \Aws\S3\S3Client([
'region' => NGALLERY['root']['storage']['s3']['credentials']['region'],
'version' => NGALLERY['root']['storage']['s3']['credentials']['version'],
'credentials' => [
'key' => NGALLERY['root']['storage']['s3']['credentials']['key'],
'secret' => NGALLERY['root']['storage']['s3']['credentials']['secret'],
],
'endpoint' => NGALLERY['root']['storage']['s3']['domains']['gateway'],
]);
2024-07-21 02:59:40 +03:00
2024-07-10 12:30:10 +03:00
$s3->putObject([
2024-07-05 07:26:39 +03:00
'Bucket' => NGALLERY['root']['storage']['s3']['credentials']['bucket'],
2024-07-13 02:47:11 +03:00
'Key' => $location.$filecdn,
2024-07-21 02:59:40 +03:00
'SourceFile' => $tmpname
2024-07-05 07:26:39 +03:00
]);
2024-07-21 02:59:40 +03:00
$this->type = $type;
2024-07-05 09:49:49 +03:00
$this->src = NGALLERY['root']['storage']['s3']['domains']['public'] . '/' . $location . $filecdn;
2024-07-21 02:59:40 +03:00
$this->size = self::human_filesize(filesize($tmpname));
$this->name = $name;
2024-07-05 09:49:49 +03:00
}
public function getType()
{
return $this->type;
}
public function getSrc()
{
return $this->src;
}
public function getSize()
{
return $this->size;
}
public function getName()
{
return $this->name;
2024-07-05 07:26:39 +03:00
}
}
2024-07-05 09:49:49 +03:00