Thinkphp,FastAdmin七牛云上传

项目场景:

fastadmin的插件要30块钱,我觉得很不错,但我是打工人,还是自己写吧,就只做了一个普通的上传,如果需要其他的功能,还是自己写或者购买插件吧。


问题描述

类找不到 Qiniu\Auth Not Found  

这个项目我也不知道有没有用composer来管理,我拿到手的时候只有一个composer的json 还没有 composer.lock,然后我从自己本地用composer下载了一个七牛云的sdk,放到vendor里面,然后出现了找不到类的情况。

composer下载命令

composer require qiniu/php-sdk

七牛云 php sdk 文档

PHP SDK_SDK 下载_对象存储 - 七牛开发者中心 (qiniu.com)icon-default.png?t=N6B9https://developer.qiniu.com/kodo/1241/php

解决方案:

找不到类的解决方案

include_once '../vendor/qiniu/php-sdk/autoload.php';

直接include引用就可以了

下面直接附上完整代码

七牛上传文件

app\common\library\QnUpload.php

<?php

namespace app\common\library;

use app\common\exception\UploadException;
use think\Config;

class QnUpload extends Upload
{

    protected $config = [];

    /**
     * @var \think\File
     */
    protected $file = null;
    protected $fileInfo = null;

    public function __construct($file = null)
    {
        include_once '../vendor/qiniu/php-sdk/autoload.php';
        parent::__construct();
        $this->config = Config::get('qiniu');
        if ($file) {
            $this->setFile($file);
        }
    }

    public function upload($savekey = null)
    {
        if (empty($this->file)) {
            throw new UploadException(__('No file upload or server upload limit exceeded'));
        }

        $this->checkSize();
        $this->checkExecutable();
        $this->checkMimetype();
        $this->checkImage();

        $savekey = $this->getSavekey();
        $savekey = '/' . ltrim($savekey, '/');
        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        $destDir = ROOT_PATH . 'public/uploads' . str_replace('/', DS, $uploadDir);

        $uDir = './uploads' . str_replace('/', DS, $uploadDir) . $fileName;

        try {
            $file = $this->file->move($destDir, $fileName);
            if (!$file) {
                // 上传失败获取错误信息
                throw new UploadException($this->file->getError());
            }
            $this->file = $file;
            $auth = new \Qiniu\Auth($this->config['accessKey'], $this->config['secretKey']);// 生成上传Token
            $token = $auth->uploadToken($this->config['bucket']);// 构建 UploadManager 对象
            $uploadMgr = new \Qiniu\Storage\UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $fileName, $uDir);
            unlink($uDir);
            if ($err !== null) {
                throw new \Exception("上传失败");
            } else {
                return $this->config['domain'] . '/' . $fileName;
            }
        } catch (\Exception $e) {
            \think\Log::error($e->getMessage());
            throw new \Exception("上传失败");
        }
    }
}

配置文件

app\extra\qiniu.php

<?php

// 七牛云配置

use think\Config;

return [
    /**
     * AccessKey
     */
    'accessKey' => Config::get('site.accessKey'),
    /**
     * SecretKey
     */
    'secretKey' => Config::get('site.secretKey'),
    /**
     * 空间名称
     */
    'bucket' => Config::get('site.bucket'),
    /**
     * 外链域名
     */
    'domain' => Config::get('site.domain'),
    /**
     * 文件保存格式
     */
    'savekey'   => '/{year}{mon}{day}/{filemd5}{.suffix}',
    /**
     * 最大可上传大小
     */
    'maxsize'   => '10mb',
    /**
     * 可上传的文件类型
     */
    'mimetype'  => 'jpg,png,bmp,jpeg,gif,zip,rar,xls,xlsx,wav,mp4,mp3,pdf',
];

 Upload.php

app\api\controller\Upload

<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\QnUpload;
use think\Config;

class Upload extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function upload()
    {
        Config::set('default_return_type', 'json');
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new QnUpload($file);
            $url = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        $this->success(__('Uploaded successful'), ['url' => $url]);
    }
}

Upload.php

原本的上传类 QnUpload继承的类

<?php

namespace app\common\library;

use app\common\exception\UploadException;
use app\common\model\Attachment;
use fast\Random;
use FilesystemIterator;
use think\Config;
use think\File;
use think\Hook;

/**
 * 文件上传类
 */
class Upload
{

    /**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 120;

    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 10;

    protected $merging = false;

    protected $chunkDir = null;

    protected $config = [];

    protected $error = '';

    /**
     * @var \think\File
     */
    protected $file = null;
    protected $fileInfo = null;

    public function __construct($file = null)
    {
        $this->config = Config::get('upload');
        $this->chunkDir = RUNTIME_PATH . 'chunks';
        if ($file) {
            $this->setFile($file);
        }
    }

    public function setChunkDir($dir)
    {
        $this->chunkDir = $dir;
    }

    public function getFile()
    {
        return $this->file;
    }

    public function setFile($file)
    {
        if (empty($file)) {
            throw new UploadException(__('No file upload or server upload limit exceeded'));
        }

        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        $fileInfo['suffix'] = $suffix;
        $fileInfo['imagewidth'] = 0;
        $fileInfo['imageheight'] = 0;

        $this->file = $file;
        $this->fileInfo = $fileInfo;
        $this->checkExecutable();
    }

    protected function checkExecutable()
    {
        //禁止上传PHP和HTML文件
        if (in_array($this->fileInfo['type'], ['text/x-php', 'text/html']) || in_array($this->fileInfo['suffix'], ['php', 'html', 'htm', 'phar', 'phtml']) || preg_match("/^php(.*)/i", $this->fileInfo['suffix'])) {
            throw new UploadException(__('Uploaded file format is limited'));
        }
        return true;
    }

    protected function checkMimetype()
    {
        $mimetypeArr = explode(',', strtolower($this->config['mimetype']));
        $typeArr = explode('/', $this->fileInfo['type']);
        //Mimetype值不正确
        if (stripos($this->fileInfo['type'], '/') === false) {
            throw new UploadException(__('Uploaded file format is limited'));
        }
        //验证文件后缀
        if ($this->config['mimetype'] === '*'
            || in_array($this->fileInfo['suffix'], $mimetypeArr) || in_array('.' . $this->fileInfo['suffix'], $mimetypeArr)
            || in_array($typeArr[0] . "/*", $mimetypeArr) || (in_array($this->fileInfo['type'], $mimetypeArr) && stripos($this->fileInfo['type'], '/') !== false)) {
            return true;
        }
        throw new UploadException(__('Uploaded file format is limited'));
    }

    protected function checkImage($force = false)
    {
        //验证是否为图片文件
        if (in_array($this->fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($this->fileInfo['suffix'], ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
            $imgInfo = getimagesize($this->fileInfo['tmp_name']);
            if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
                throw new UploadException(__('Uploaded file is not a valid image'));
            }
            $this->fileInfo['imagewidth'] = isset($imgInfo[0]) ? $imgInfo[0] : 0;
            $this->fileInfo['imageheight'] = isset($imgInfo[1]) ? $imgInfo[1] : 0;
            return true;
        } else {
            return !$force;
        }
    }

    protected function checkSize()
    {
        preg_match('/([0-9\.]+)(\w+)/', $this->config['maxsize'], $matches);
        $size = $matches ? $matches[1] : $this->config['maxsize'];
        $type = $matches ? strtolower($matches[2]) : 'b';
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)($size * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0));
        if ($this->fileInfo['size'] > $size) {
            throw new UploadException(__('File is too big (%sMiB). Max filesize: %sMiB.',
                round($this->fileInfo['size'] / pow(1024, 2), 2),
                round($size / pow(1024, 2), 2)));
        }
    }

    public function getSuffix()
    {
        return $this->fileInfo['suffix'] ?: 'file';
    }

    public function getSavekey($savekey = null, $filename = null, $md5 = null)
    {
        if ($filename) {
            $suffix = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        } else {
            $suffix = $this->fileInfo['suffix'];
        }
        $filename = $filename ? $filename : ($suffix ? substr($this->fileInfo['name'], 0, strripos($this->fileInfo['name'], '.')) : $this->fileInfo['name']);
        $md5 = $md5 ? $md5 : md5_file($this->fileInfo['tmp_name']);
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => substr($filename, 0, 100),
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => $md5,
        ];
        $savekey = $savekey ? $savekey : $this->config['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        return $savekey;
    }

    /**
     * 清理分片文件
     * @param $chunkid
     */
    public function clean($chunkid)
    {
        if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
            throw new UploadException(__('Invalid parameters'));
        }
        $iterator = new \GlobIterator($this->chunkDir . DS . $chunkid . '-*', FilesystemIterator::KEY_AS_FILENAME);
        $array = iterator_to_array($iterator);
        foreach ($array as $index => &$item) {
            $sourceFile = $item->getRealPath() ?: $item->getPathname();
            $item = null;
            @unlink($sourceFile);
        }
    }

    /**
     * 合并分片文件
     * @param string $chunkid
     * @param int    $chunkcount
     * @param string $filename
     * @return attachment|\think\Model
     * @throws UploadException
     */
    public function merge($chunkid, $chunkcount, $filename)
    {
        if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
            throw new UploadException(__('Invalid parameters'));
        }

        $filePath = $this->chunkDir . DS . $chunkid;

        $completed = true;
        //检查所有分片是否都存在
        for ($i = 0; $i < $chunkcount; $i++) {
            if (!file_exists("{$filePath}-{$i}.part")) {
                $completed = false;
                break;
            }
        }
        if (!$completed) {
            $this->clean($chunkid);
            throw new UploadException(__('Chunk file info error'));
        }

        //如果所有文件分片都上传完毕,开始合并
        $uploadPath = $filePath;

        if (!$destFile = @fopen($uploadPath, "wb")) {
            $this->clean($chunkid);
            throw new UploadException(__('Chunk file merge error'));
        }
        if (flock($destFile, LOCK_EX)) { // 进行排他型锁定
            for ($i = 0; $i < $chunkcount; $i++) {
                $partFile = "{$filePath}-{$i}.part";
                if (!$handle = @fopen($partFile, "rb")) {
                    break;
                }
                while ($buff = fread($handle, filesize($partFile))) {
                    fwrite($destFile, $buff);
                }
                @fclose($handle);
                @unlink($partFile); //删除分片
            }

            flock($destFile, LOCK_UN);
        }
        @fclose($destFile);

        $attachment = null;
        try {
            $file = new File($uploadPath);
            $info = [
                'name'     => $filename,
                'type'     => $file->getMime(),
                'tmp_name' => $uploadPath,
                'error'    => 0,
                'size'     => $file->getSize()
            ];
            $file->setSaveName($filename)->setUploadInfo($info);
            $file->isTest(true);

            //重新设置文件
            $this->setFile($file);

            unset($file);
            $this->merging = true;

            //允许大文件
            $this->config['maxsize'] = "1024G";

            $attachment = $this->upload();
        } catch (\Exception $e) {
            @unlink($destFile);
            throw new UploadException($e->getMessage());
        }
        return $attachment;
    }

    /**
     * 分片上传
     * @throws UploadException
     */
    public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false)
    {

        if ($this->fileInfo['type'] != 'application/octet-stream') {
            throw new UploadException(__('Uploaded file format is limited'));
        }

        if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
            throw new UploadException(__('Invalid parameters'));
        }

        $destDir = RUNTIME_PATH . 'chunks';
        $fileName = $chunkid . "-" . $chunkindex . '.part';
        $destFile = $destDir . DS . $fileName;
        if (!is_dir($destDir)) {
            @mkdir($destDir, 0755, true);
        }
        if (!move_uploaded_file($this->file->getPathname(), $destFile)) {
            throw new UploadException(__('Chunk file write error'));
        }
        $file = new File($destFile);
        $info = [
            'name'     => $fileName,
            'type'     => $file->getMime(),
            'tmp_name' => $destFile,
            'error'    => 0,
            'size'     => $file->getSize()
        ];
        $file->setSaveName($fileName)->setUploadInfo($info);
        $this->setFile($file);
        return $file;
    }

    /**
     * 普通上传
     * @return \app\common\model\attachment|\think\Model
     * @throws UploadException
     */
    public function upload($savekey = null)
    {
        if (empty($this->file)) {
            throw new UploadException(__('No file upload or server upload limit exceeded'));
        }

        $this->checkSize();
        $this->checkExecutable();
        $this->checkMimetype();
        $this->checkImage();

        $savekey = $savekey ? $savekey : $this->getSavekey();
        $savekey = '/' . ltrim($savekey, '/');
        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);

        $destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir);

        $sha1 = $this->file->hash();

        //如果是合并文件
        if ($this->merging) {
            if (!$this->file->check()) {
                throw new UploadException($this->file->getError());
            }
            $destFile = $destDir . $fileName;
            $sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
            $info = $this->file->getInfo();
            $this->file = null;
            if (!is_dir($destDir)) {
                @mkdir($destDir, 0755, true);
            }
            rename($sourceFile, $destFile);
            $file = new File($destFile);
            $file->setSaveName($fileName)->setUploadInfo($info);
        } else {
            $file = $this->file->move($destDir, $fileName);
            if (!$file) {
                // 上传失败获取错误信息
                throw new UploadException($this->file->getError());
            }
        }
        $this->file = $file;
        $category = request()->post('category');
        $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
        $auth = Auth::instance();
        $params = array(
            'admin_id'    => (int)session('admin.id'),
            'user_id'     => (int)$auth->id,
            'filename'    => mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
            'category'    => $category,
            'filesize'    => $this->fileInfo['size'],
            'imagewidth'  => $this->fileInfo['imagewidth'],
            'imageheight' => $this->fileInfo['imageheight'],
            'imagetype'   => $this->fileInfo['suffix'],
            'imageframes' => 0,
            'mimetype'    => $this->fileInfo['type'],
            'url'         => 'https://kk.ttxcx.net'.$uploadDir . $file->getSaveName(),
            'uploadtime'  => time(),
            'storage'     => 'local',
            'sha1'        => $sha1,
            'extparam'    => '',
        );
        $attachment = new Attachment();
        $attachment->data(array_filter($params));
        $attachment->save();

        \think\Hook::listen("upload_after", $attachment);
        return $attachment;
    }

    public function setError($msg)
    {
        $this->error = $msg;
    }

    public function getError()
    {
        return $this->error;
    }
}

其他的好几个上传的引用的 我都换成七牛的了

//默认普通上传文件
            $file = $this->request->file('file');
            try {
//                $upload = new Upload($file);
//                $attachment = $upload->upload();
                $upload = new QnUpload($file);
                $url = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            //$this->success(__('Uploaded successful'), ['url' => $attachment->url]); //, 'fullurl' => cdnurl($attachment->url, true)
            $this->success(__('Uploaded successful'), ['url' => $url]);

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
关于 FastAdmin 或者 ThinkPHP 的 iOS 支付代码,可以按照以下步骤进行: 1. 在苹果开发者中心创建 App ID,并开通 In-App Purchase 功能。 2. 在 Xcode 中创建一个新的 iOS 项目,并在项目设置中配置好 Bundle ID 和开发者账号。 3. 添加 StoreKit.framework 和 StoreKit 库文件到项目中。 4. 在代码中导入 StoreKit 框架,并实现 SKPaymentTransactionObserver 协议和 SKProductsRequestDelegate 协议。 5. 调用 SKProductsRequest 请求商品信息,并在回调中获取到商品信息。 6. 根据商品信息调用 SKPaymentQueue 发起支付请求,并在回调中处理支付结果。 以下是一个简单的示例代码: ```swift import UIKit import StoreKit class ViewController: UIViewController, SKPaymentTransactionObserver, SKProductsRequestDelegate { override func viewDidLoad() { super.viewDidLoad() // 监听支付状态 SKPaymentQueue.default().add(self) } // 请求商品信息 func requestProductsInfo() { let productIdentifiers = Set(["com.example.product1"]) let request = SKProductsRequest(productIdentifiers: productIdentifiers) request.delegate = self request.start() } // 获取商品信息回调 func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { if response.products.count > 0 { let product = response.products[0] let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } } // 支付状态回调 func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch transaction.transactionState { case .purchased: // 支付成功 SKPaymentQueue.default().finishTransaction(transaction) break case .failed: // 支付失败 SKPaymentQueue.default().finishTransaction(transaction) break case .restored: // 恢复购买 SKPaymentQueue.default().finishTransaction(transaction) break default: break } } } } ``` 这个示例代码中,通过实现 SKPaymentTransactionObserver 协议和 SKProductsRequestDelegate 协议,请求商品信息并发起支付请求,然后在支付状态回调中处理支付结果。需要注意的是,这个示例代码中的商品 ID 需要根据实际情况进行替换。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值