当前位置:网站首页>PHP uses Alibaba cloud storage

PHP uses Alibaba cloud storage

2022-07-07 23:21:00 Code is a bug

Alibaba cloud object storage website

Alibaba cloud object storage website

Install alicloud sdk

Use composer Install or use other methods according to the official website

composer require aliyuncs/oss-sdk-php

Upload files

<?php

use OSS\OssClient;
use OSS\Core\OssException;

if (is_file(__DIR__ . '/../autoload.php')) {
    
    require_once __DIR__ . '/../autoload.php';
}

if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    
    require_once __DIR__ . '/../vendor/autoload.php';
}

class OssUpload
{
    
    public function upload($file)
    {
    
       //  Alicloud account AccessKey Have all the API Access rights of , The risk is high . It is highly recommended that you create and use it RAM The user carries out API Visit or daily operations , Please log in RAM Console creation RAM user .
        $accessKeyId = "yourAccessKeyId";
        $accessKeySecret = "yourAccessKeySecret";
       // yourEndpoint Fill in Bucket The region corresponding to Endpoint. East China 1( Hangzhou ) For example ,Endpoint Fill in for https://oss-cn-hangzhou.aliyuncs.com.
        $endpoint = "yourEndpoint";
      //  Fill in Bucket name , for example examplebucket.
         $bucket= "examplebucket";
        //  Fill in Object The full path , for example exampledir/exampleobject.txt.Object The full path cannot contain Bucket name .
        $object = "uploads/".date('Y',time()).date('m',time()).date('d',time())."/".$file['name'];  //  Storage path of files in Alibaba cloud 
        // <yourLocalFile> By the local file path plus file name including suffixes , for example /users/local/myfile.txt.
        //  Fill in the full path of the local file , for example D:\\localpath\\examplefile.txt. If no local path is specified , By default, the file is uploaded from the local path corresponding to the project to which the sample program belongs .
        $filePath =$file['tmp_name'];    //  File path 
        try {
    
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch
        (OssException $e) {
    
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
// print(__FUNCTION__ . "OK" . "\n");
        return $object;   //  Upload successful , Return file path 
    }


}

  <?php
namespace app\app\controller;
use app\app\model\AppLandpoint;
use app\common\controller\Api;
use app\common\controller\OssUpload;
class LandPoint
{
    
    /* * @description  Photo upload */

    public function ImgUpload() {
    
        $file=$_FILES['img'];
        $upload=new OssUpload();
        $data=$upload->upload($file);
        return json(['code','data'=>$data]);
    }
}
原网站

版权声明
本文为[Code is a bug]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072031469429.html