Rumah > rangka kerja php > Laravel > Kongsi kod utama untuk memuat naik dan menandatangani fail dalam persekitaran awan OSS

Kongsi kod utama untuk memuat naik dan menandatangani fail dalam persekitaran awan OSS

藏色散人
Lepaskan: 2023-01-17 14:09:30
ke hadapan
1109 orang telah melayarinya

Muat naik dan tandatangan fail OSS

Saya percaya bahawa dalam pembangunan harian, anda sering menggunakan fungsi seperti memuat naik dan memuat turun fail awan, dan Alibaba Cloud dan Huawei Cloud biasanya digunakan di China . Laravel mempunyai Storan yang disertakan tidak mempunyai sokongan mesra secara lalai.

Kebetulan terdapat pelbagai jenis loya semasa proses pemindahan awan baru-baru ini, terutamanya berkaitan antara muka muat naik dan tandatangan. Kod utama untuk memuat naik dan menandatangani fail dalam persekitaran awan OSS direkodkan khas untuk rujukan.

Arahan pemasangan pakej berkaitan:

// 阿里云oss
composer require aliyuncs/oss-sdk-php
// 华为云obs
composer require obs/esdk-obs-php
Salin selepas log masuk

Sila beri perhatian kepada versi pakej dan sama ada ia boleh digunakan pada versi php.

.env Item konfigurasi:

# OSS相关配置
OSS_DRIVER=HW_OBS
#华为OBS
OSS_HW_ENDPOINT=https://obs.cn-east-3.myhuaweicloud.com
OSS_HW_KEY=ME0AVBTNJTSJB2LH0EGI
OSS_HW_SECRET=eCGffrwdx3Rt5QEmKbtEvruvGgg1mCUjMsnHfjWo
OSS_HW_BUCKET=pub-obs-test-1
#阿里云
OSS_ENDPOINT=https://oss-cn-hangzhou.aliyuncs.com
OSS_KEYID=LTAI4Ftno9DsfiVHADX73osa
OSS_KEYSECRET=vo9KuqgaDN727eOOz1tDg77Egeg7wE
OSS_BUCKET=xgimi-ipr
Salin selepas log masuk

Kod:

1

2. Pelaksanaan OSS Alibaba
<?php
namespace App\Service\OSS;
interface IOSS
{
    /**
     * 上传
     *
     * @param $fullFileName
     * @param $filePath
     * @return mixed
     */
    public function publicUpload($fullFileName, $filePath);
    /**
     * url验签、下载
     *
     * @param $fullFileName | 含前缀的完整url文件名
     * @param $expires      |   过期时效
     * @return mixed
     */
    public function getUrl($fullFileName, $expires);
    /**
     * 可替换url域名
     *
     * @param $url
     * @return mixed
     */
    public function replaceUrl($url);
}
Salin selepas log masuk

3. Pelaksanaan OBS Huawei
<?php
namespace App\Service\OSS;
use OSS\OssClient;
class AliOSS implements IOSS
{
    private $endPoint;
    private $keyId;
    private $secret;
    private $bucket;
    private $ossClient;
    private $expires = 3 * 24 * 3600;
    private $aliHost = &#39;&#39;;
    private $myHost = &#39;&#39;;
    public function __construct()
    {
        $this->endPoint = env("OSS_ENDPOINT");
        $this->keyId = env("OSS_KEYID");
        $this->secret = env("OSS_KEYSECRET");
        $this->bucket = env("OSS_BUCKET");
        try {
            $this->ossClient = new OssClient($this->keyId, $this->secret, $this->endPoint);
        } catch (\Exception $e) {
        }
    }
    /**
     * 上传
     *
     * @param $fullFileName
     * @param $filePath
     * @return mixed
     * @throws \Exception
     */
    public function publicUpload($fullFileName, $filePath)
    {
        return $this->ossClient->uploadFile($this->bucket, $fullFileName, $filePath);
    }
    /**
     * url验签、下载
     *
     * @param $fullFileName
     * @param $expires |   过期时效
     * @return mixed
     * @throws \Exception
     */
    public function getUrl($fullFileName, $expires)
    {
        $expires = $expires ? $expires : $this->expires;
        $signUrl = $this->ossClient->signUrl($this->bucket, $fullFileName, $expires);
        return $signUrl;
    }
    /**
     * 替换url域名
     *
     * @param $url
     * @return mixed
     */
    public function replaceUrl($url)
    {
        return str_replace($this->aliHost, $this->myHost, $url);
    }
}
Salin selepas log masuk

Demo: logik perniagaan + kelas OSS
<?php
namespace App\Service\OSS;
use Obs\ObsClient;
class HuaweiOBS implements IOSS
{
    private $endPoint;
    private $key;
    private $secret;
    private $bucket;
    private $obsClient;
    private $expires = 3 * 24 * 3600;
    private $hwHost = &#39;&#39;;
    private $myHost = &#39;&#39;;
    public function __construct()
    {
        $this->endPoint = env("OSS_HW_ENDPOINT");
        $this->key = env("OSS_HW_KEY");
        $this->secret = env("OSS_HW_SECRET");
        $this->bucket = env("OSS_HW_BUCKET");
        try {
            $this->obsClient = new ObsClient([&#39;key&#39; => $this->key, &#39;secret&#39; => $this->secret, &#39;endpoint&#39; => $this->endPoint]);
        } catch (\Exception $e) {
        }
    }
    /**
     * 上传
     *
     * @param $fullFileName
     * @param $filePath
     * @return mixed
     */
    public function publicUpload($fullFileName, $filePath)
    {
        $res = $this->obsClient->putObject([
            &#39;Bucket&#39; => $this->bucket,
            &#39;Key&#39; => $fullFileName,
            &#39;SourceFile&#39; => $filePath
        ]);
        return $res;
    }
    /**
     * url验签、下载
     *
     * @param $fullFileName
     * @param $expires |   过期时效
     * @return mixed
     * @throws \Exception
     */
    public function getUrl($fullFileName, $expires)
    {
        $expires = $expires ? $expires : $this->expires;
        // 生成下载对象的带授权信息的URL
        $res = $this->obsClient->createSignedUrl([
            &#39;Method&#39; => &#39;GET&#39;,
            &#39;Bucket&#39; => $this->bucket,
            &#39;Key&#39; => $fullFileName,
            &#39;Expires&#39; => $expires
        ]);
        return $res[&#39;SignedUrl&#39;];
    }
    /**
     * 替换url域名
     *
     * @param $url
     * @return mixed
     */
    public function replaceUrl($url)
    {
        return str_replace($this->hwHost, $this->myHost, $url);
    }
}
Salin selepas log masuk

<?php
namespace App\Service;
class UploadFile
{
    /**
     * 文件上传 带签名访问
     *
     * @param        $files
     * @param string $prefix
     * @return array 
     * @throws \Exception
     */
    public static function upload($files, $prefix = &#39;&#39;)
    {
        if (empty($files)) {
            return [&#39;ok&#39; => false, &#39;message&#39; => &#39;请上传文件!&#39;];
        }
        if (is_array($files)) {
            $pics = [];
            foreach ($files as $key => $file) {
                if ($file->isValid()) {
                    $name = $file->getClientOriginalName();
                    $fullName = OSS::getFullFileName($name, $prefix);
                    $ret = OSS::publicUpload($fullName, $file, $prefix);
                    if ($ret) {
                        $url = OSS::getUrl($fullName);
                        $url = OSS::replaceUrl($url);
                        $pics[] = [&#39;name&#39; => $name, &#39;url&#39; => $url, &#39;file_name&#39; => $fullName];
                    }
                } else {
                    return [&#39;ok&#39; => false, &#39;message&#39; => &#39;无效文件!&#39;];
                }
            }
            if (count($pics) > 0) {
                return [&#39;ok&#39; => true, &#39;data&#39; => $pics];
            }
        } else {
            $name = $files->getClientOriginalName();
            $fullName = OSS::getFullFileName($name, $prefix);
            $ret = OSS::publicUpload($fullName, $files, $prefix);
            if ($ret) {
                $url = OSS::getUrl($fullName);
                $url = OSS::replaceUrl($url);
                return [&#39;ok&#39; => true, &#39;data&#39; => [&#39;name&#39; => $name, &#39;url&#39; => $url, &#39;file_name&#39; => $fullName]];
            } else {
                return [&#39;ok&#39; => false, &#39;message&#39; => &#39;无效文件!&#39;];
            }
        }
    }
}
Salin selepas log masuk
Jika anda mempunyai masa, anda boleh menambah antara muka fungsinya dan memperkayakan lebih banyak keupayaan antara muka awan.
<?php
namespace App\Service;
use App\Service\OSS\AliOSS;
use App\Service\OSS\HuaweiOBS;
use Exception;
class OSS
{
    const DEFAULT_DRIVER = &#39;HW_OBS&#39;;
    const OSS_PREFIX = &#39;oss/&#39;;
    public $OSSService;
    /**
     * 初始化 service
     */
    public function __construct()
    {
        if (env(&#39;OSS_DRIVER&#39;) === self::DEFAULT_DRIVER) {
            $this->OSSService = new HuaweiOBS();
        } else {
            $this->OSSService = new AliOSS();
        }
    }
    public static function getInstance()
    {
        return new self();
    }
    /**
     * 使用外网上传文件
     *
     * @param $fullName
     * @param $filePath
     * @param $prefix
     * @return mixed
     * @throws Exception
     */
    public static function publicUpload($fullName, $filePath, $prefix)
    {
        return self::getInstance()->OSSService->publicUpload($fullName, $filePath);
    }
    /**
     * 获取oss图片url
     *
     * @param $fullName
     * @param $expires |    过期时效
     * @return string
     * @throws Exception
     */
    public static function getUrl($fullName, $expires = &#39;&#39;)
    {
        return self::getInstance()->OSSService->getUrl($fullName, $expires);
    }
    /**
     * 替换url域名
     *
     * @param $url
     * @return mixed
     */
    public static function replaceUrl($url)
    {
        return self::getInstance()->OSSService->replaceUrl($url);
    }
    /**
     * 获取完整的文件名含路径
     *
     * @param $fileName
     * @param $prefix
     * @return string
     */
    public static function getFullFileName($fileName, $prefix)
    {
        return self::OSS_PREFIX . $prefix . self::setFileName($fileName);
    }
    /**
     * 设置新的文件名(重命名规则)
     *
     * @param $fileName
     * @return string
     */
    public static function setFileName($fileName)
    {
        $nameArray = explode(&#39;.&#39;, $fileName);
        $extension = $nameArray[count($nameArray) - 1];
        $newName = date(&#39;Ymd&#39;) . &#39;/&#39; . date(&#39;YmdHis&#39;) . rand(10000, 99999) . &#39;.&#39; . $extension;
        return $newName;
    }
}
Salin selepas log masuk

Lampiran:

pakej komposer: https://packagist.org/packages/league/flysystem

Pakej mvn musim bunga: https ://spring-file-storage.xuyanwu.cn/#/ |. https://spring-file-storage.xuyanwu.cn/#/
composer require league/flysystem
Salin selepas log masuk

Pembelajaran yang disyorkan: "

tutorial video laravel

Atas ialah kandungan terperinci Kongsi kod utama untuk memuat naik dan menandatangani fail dalam persekitaran awan OSS. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
oss
sumber:learnku.com
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan