I. install Alibaba cloud oss sdk

1. Install oss sdk by executing the following commands in the website root directory.

composer require aliyuncs/oss-sdk-php

After installation, a folder named aliyuncs will be found under the website root directory / vendor.

Note: Aliyun oss - sdk document (no need to pay attention) "Official oss - sdk document"

 

Two, use

1. Get OSS AccessKeyId, AccessKeySecret

If there are no two data to refer to How to Get OSS Access Key Id, Access Key Secret .

 
2. Simple Upload Html Processing

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Xiao Butuo Personal Station - oss Picture upload</title>
</head>
<body>
    <form action="oss-image/upload-image.json" method="post" enctype="multipart/form-data">
        <label for="file">Filename:</label>
        <input type="file" name="image" id="file"><br>
        <input type="submit" name="submit" value="Submission">
    </form>
</body>
</html>

 
3. Controller handles OssImageController.php (send requests directly to service without paying attention to this layer)

<?php
declare(strict_types = 1);

namespace app\controllers;

use app\services\OssImageService;

class OssImageController extends BaseController
{
    /**
     * oss Upload pictures
     *
     * @return string
     * @throws \OSS\Core\OssException
     */
    public function actionUploadImage()
    {
        return $this->response(OssImageService::service()->uploadImage());
    }
}

 
4. service layer processes OssImageService.php (PHP process in this layer, just pay attention to this layer)

<?php
declare(strict_types = 1);

namespace app\services;

use app\extensions\AliOss;

class OssImageService extends BaseService
{
    /**
     * oss Upload pictures
     *
     * @return array
     * @throws \OSS\Core\OssException
     */
    public function uploadImage()
    {

            $ossClient  = AliOss::getOssClient();
            $bucketName = AliOss::getBucketName();
            // file name
            $fileName = $_FILES['image']['name'];
            // Temporary file location
            $tmpFile = $_FILES['image']['tmp_name'];
            // Define the oss location for file storage
            $ossPath = 'test/'.date('Y-m-d').'/'.date('Hi') .mt_rand(10000,99999);
            // Define oss object
            $object = $ossPath .'.' .$this->getExtension($fileName);
            // Execute upload and get back oss information
            $info = $ossClient->uploadFile($bucketName, $object, $tmpFile);
            $ossUrl = $info['oss-request-url'];
            // If the picture protocol is http, it is converted to https
            if (substr($ossUrl, 0, 4) == 'http') {
                $ossUrl = substr_replace($ossUrl, 'https', 0, 4);
            }
            $data = [
                'file_url'  => $ossUrl,
                'file_name' => basename($ossUrl)
            ];
            return $data;
    }

    /**
     * Returns the file extension
     *
     * @param $fileName
     * @return mixed
     */
    private function getExtension($fileName)
    {
        return pathinfo($fileName)['extension'];
    }
}

 
5. oss instance and parameter acquisition package AliOss.php

<?php
declare(strict_types = 1);

namespace app\extensions;

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

/**
 *Aliyun oss file upload
 */
class AliOss
{
    const endpoint        = 'oss-cn-hongkong.aliyuncs.com';
    const accessKeyId     = 'LSDFskkdDDSSdkfg';
    const accessKeySecret = 'LT9cG3JkGKffRPalgk4n33lk8Ll41d';
    const bucket          = 'hk-server';

    /**
     * According to Config configuration, get an OssClient instance
     *
     * @return OssClient An OssClient instance
     */
    public static function getOssClient()
    {
        try {
            $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
        } catch (OssException $e) {
            printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
            printf($e->getMessage() . "\n");
            return null;
        }

        return $ossClient;
    }

    public static function getBucketName()
    {
        return self::bucket;
    }
    
}

 
6. The result is that it can upload successfully and return the full access url of the picture in oss.

{
    status: 1,
    msg: "success",
    data: {
        file_url: "http://hk-server.oss-cn-hongkong.aliyuncs.com/test/2018-08-22/211753008.jpg",
        file_name: "211753008.jpg"
    }
}

At this time, we visited http://hk-server.oss-cn-hongkong.aliyuncs.com/test/2018-08-22/211753008.jpg You can get the pictures normally, and you can find the uploaded files in the oss management console.

This is just uploading the file to oss and returning the URL of the file to the front end, but the information of the file has not been stored locally. It is suggested that after receiving the url, the front end, together with other data of the file (such as classification, file name, etc.), requests another interface of the back end to store the information of the local database.

 

III. Problem statement

The OSS Access Key Id you provided did not exist in our records and so on. Don't panic, just regenerate it.

In addition, we can refer to this kind of errors in the official return of Aliyun oss. Official error checking of oss .