七牛云上傳文件,php,Demo

<?php

namespace app\common\library\storage\engine;

use think\Exception;

use think\Request;

/**

  • 存儲引擎抽象類

  • Class server

  • @package app\common\library\storage\drivers

*/

abstract class Server

{

protected $file;

protected $error;

protected $fileName;

protected $fileInfo;

/**

* 構造函數

* Server constructor.

* @throws Exception

*/

protected function __construct()

{

    // 接收上傳的文件

    $this->file = Request::instance()->file('iFile');

    if (empty($this->file)) {

        throw new Exception('未找到上傳文件的信息');

    }

    // 生成保存文件名

    $this->fileName = $this->buildSaveName();

    // 文件信息

    $this->fileInfo = $this->file->getInfo();

}

/**

* 文件上傳

* @return mixed

*/

abstract protected function upload();

/**

* 返回上傳后文件路徑

* @return mixed

*/

abstract public function getFileName();

/**

* 返回文件信息

* @return mixed

*/

public function getFileInfo()

{

    return $this->fileInfo;

}

/**

* 返回錯誤信息

* @return mixed

*/

public function getError()

{

    return $this->error;

}

/**

* 生成保存文件名

*/

private function buildSaveName()

{

    // 要上傳圖片的本地路徑

    $realPath = $this->file->getRealPath();

    // 擴展名

    $ext = pathinfo($this->file->getInfo('name'), PATHINFO_EXTENSION);

    // 自動生成文件名

    return date('YmdHis') . substr(md5($realPath), 0, 5)

        . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT) . '.' . $ext;

}

}

<?php

namespace app\common\library\storage\engine;

use Qiniu\Auth;

use Qiniu\Storage\UploadManager;

/**

  • 七牛云存儲引擎

  • Class Qiniu

  • @package app\common\library\storage\engine

*/

class Qiniu extends Server

{

private $config;

/**

* 構造方法

* Qiniu constructor.

* @param $config

* @throws \think\Exception

*/

public function __construct($config)

{

    parent::__construct();

    $this->config = $config;

}

/**

* 執(zhí)行上傳

* @return bool|mixed

* @throws \Exception

*/

public function upload()

{

    // 要上傳圖片的本地路徑

    $realPath = $this->file->getRealPath();

    // 構建鑒權對象

    $auth = new Auth($this->config['access_key'], $this->config['secret_key']);

    // 要上傳的空間

    $token = $auth->uploadToken($this->config['bucket']);

    // 初始化 UploadManager 對象并進行文件的上傳

    $uploadMgr = new UploadManager();

    // 調用 UploadManager 的 putFile 方法進行文件的上傳

    list($result, $error) = $uploadMgr->putFile($token, $this->fileName, $realPath);

    if ($error !== null) {

        $this->error = $error->message();

        return false;

    }

    return true;

}

/**

* 返回文件路徑

* @return mixed

*/

public function getFileName()

{

    return $this->fileName;

}

}

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容