简体   繁体   English

如何在yii2中自定义s3上传文件的URL?

[英]How to customize s3 uploaded files url in yii2?

I have used vlaim\\fileupload\\FileUpload; 我用过vlaim\\fileupload\\FileUpload; and yii\\web\\UploadedFile; yii\\web\\UploadedFile;

$image = UploadedFile::getInstance($model, 'flag');
            $model->flag = new FileUpload(FileUpload::S_S3, [
                'version' => 'latest',
                'region' => 'us-west-2',
                'credentials' => [
                    'key' => 'KEY',
                    'secret' => 'SECRET'
                ],
                'bucket' => 'mybucket/uploads/flags/'.$model->code
            ]);
            $uploader = $model->flag;
            $model->flag = $uploader->uploadFromFile($image)->path;

In db i'm saving the path. 在数据库中,我保存路径。 How to customize the url? 如何自定义网址?

Now my url looks like https://s3-us-west-2.amazonaws.com/mybucket%2Fuploads%2Fflags%2Fus/uploads%5C9f%5C7e%5Cc093ad5a.png 现在我的网址看起来像https://s3-us-west-2.amazonaws.com/mybucket%2Fuploads%2Fflags%2Fus/uploads%5C9f%5C7e%5Cc093ad5a.png

I need the url like https://mybucket.s3.amazonaws.com/uploads/flags/us.png 我需要类似https://mybucket.s3.amazonaws.com/uploads/flags/us.png

S3 does not have the concept of folders, It is an object store, with key/value pairs. S3没有文件夹的概念,它是一个具有键/值对的对象存储。 They key for your file would be uploads/flags/us.png 他们对您文件的关键是uploads/flags/us.png

with the PHP SDK it's easy to set the key of the object. 使用PHP SDK,可以轻松设置对象的键。

$USAGE = "\n" .
    "To run this example, supply the name of an S3 bucket and a file to\n" .
    "upload to it.\n" .
    "\n" .
    "Ex: php PutObject.php <bucketname> <filename>\n";
if (count($argv) <= 2){
    echo $USAGE;
    exit();
}
$bucket = $argv[1];
$file_Path = $argv[2];
$key = basename($argv[2]);
try{
    //Create a S3Client
    $s3Client = new S3Client([
        'region' => 'us-west-2',
        'version' => '2006-03-01'
    ]);
    $result = $s3Client->putObject([
        'Bucket'     => $bucket,
        'Key'        => $key,
        'SourceFile' => $file_Path,
    ]);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

yii2 i think you need to set setFsUrl() yii2我认为您需要设置setFsUrl()

http://www.yiiframework.com/extension/yii2-file-upload/#hh8 http://www.yiiframework.com/extension/yii2-file-upload/#hh8

setFsUrl(string $url)

(Only for Local mode)

Sets url. For example, if you set path to 'http://static.example.com' file after uploading will have URL http://static.example.com/path/to/your/file

Default to /

php $uploader->setFsPath('http://pathtoyoursite.com');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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