fastadmin 文件上传七牛云

1-安装七牛云官方SDK

composer require qiniu/php-sdk

2-七牛云配置

<?php

namespace app\common\controller;

use Qiniu\Storage\BucketManager;
use think\Config;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Controller;
use think\Db;

/**
 * 七牛基类
 */
class Qiniu extends Controller
{

    /** * 上传
     * @param array $file 图片参数
     * @return array
     */
    public function uploadOne($config)
    {
        $data = $this->request->file();
        $info = $data['file']->getInfo();

        $domain = $config['qiniu_domain'];
        $bucket = $config['qiniu_bucket'];
        $auth = new Auth($config['qiniu_accesskey'], $config['qiniu_secretkey']);
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        $parts = explode('.', $info['name']);
        $extension = end($parts);
        $filename=hash('md5', uniqid()).mt_rand(1,99).'.'.$extension;
        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, 'uploads/'.$filename, $info['tmp_name']);
        if ($err !== null) {
            return ['code' => 0,  'msg' => '上传失败'];
        } else {
            //返回图片的完整URL
            Db::name('attachment')->insert([
                'filesize'    => $info['size'],
                'imagetype'   => $info['type'],
                'imageframes' => 0,
                'mimetype'    => $info['type'],
                'filename'    => $filename,
                'url'         => $ret['key'],
                'createtime'  => time(),
                'updatetime'  => time(),
                'uploadtime'  => time(),
                'storage'     => 'qiniu',
                'sha1'        => '',
                'type'        => 2,
                'type_url'    => $domain,
                'extparam'    => '',
                ]);
            return ['code' => 1, 'msg' => '上传完成', 'data' => ($domain . $ret['key'])];
        }
    }

    public function deleteOne($imageName,$config)
    {
        // 构建认证
        $auth = new Auth($config['qiniu_accesskey'], $config['qiniu_secretkey']);
        // 构建请求
        $bucketMgr = new BucketManager($auth);
        // 要删除的文件的名称,包括你设置的前缀
        $key = $imageName;
        // 要删除文件的空间
        $bucket = $config['qiniu_bucket'];
        list($ret, $err) = $bucketMgr->delete($bucket, $key);
        if ($err !== null) {
            // 处理错误
            Checking::writeLog($err->message(),'删除失败','qiniu.log');
        } else {
            // 删除成功
            Checking::writeLog('删除成功','ok','qiniu.log');
        }
    }
}

 接下来修改fastadmin 上传文件  api/controller/Common.php 文件下的 upload 方法

<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\captcha\Captcha;
use think\Config;
use think\Db;
use think\Hook;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'captcha','upload'];
    protected $noNeedRight = '*';
    protected $config;

    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
        $this->config=Db::name('config')->where(['group'=>'attachment'])->column('value','name');

    }

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            switch ($this->config['attachment_type']){
                case 2:
                    $qiniu = new \app\common\controller\Qiniu;
                    $attachment = $qiniu->uploadOne($this->config);
                    if ($attachment["code"] == 0) {
                        $this->error($attachment["msg"]);
                    }
                    $this->success(__('Uploaded successful'), '', ['url' => $attachment['data'], 'fullurl' => cdnurl($attachment['data'], true)]);
                    break;
                case 3:
                    $tencent= new \app\common\controller\Tencent;
                    $attachment = $tencent->uploadToTencentCloud($this->config);
                    if ($attachment["code"] == 0) {
                        $this->error($attachment["msg"]);
                    }
                    $this->success(__('Uploaded successful'), '', ['url' => $attachment['data'], 'fullurl' => cdnurl($attachment['data'], true)]);
                    break;
                case 4:
                    break;
                default:
                    //默认普通上传文件
                    $attachment = null;
                    //默认普通上传文件
                    $file = $this->request->file('file');
                    try {
                        $upload = new Upload($file);
                        $attachment = $upload->upload();
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                    $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
                    break;
            }
//            $attachment = null;
//            //默认普通上传文件
//            $file = $this->request->file('file');
//            try {
//                $upload = new Upload($file);
//                $attachment = $upload->upload();
//            } catch (UploadException $e) {
//                $this->error($e->getMessage());
//            } catch (\Exception $e) {
//                $this->error($e->getMessage());
//            }
//
//            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    /**
     * 验证码
     * @param $id
     * @return \think\Response
     */
    public function captcha($id = "")
    {
        \think\Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH'   => 150,
                'imageW'   => 350,
            ])
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }
}

接下来修改附件选择器 admin/controller/general/Attachment.php 下的index方法


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 要关闭fastadmin中的七牛云功能,可以按照以下步骤进行操作: 1. 登录到FastAdmin后台管理界面。 2. 在左侧导航菜单中找到并点击「系统设置」选项。 3. 在系统设置页面中,找到并点击「上传设置」选项卡。 4. 在上传设置选项卡中,找到「云存储类型」的设置项。 5. 将「云存储类型」设置为「本地存储」,表示关闭了七牛云。 6. 保存设置并退出系统设置页面。 通过以上步骤,即可将fastadmin中的七牛云功能关闭。此时,系统将使用本地存储来管理和存储上传的文件,而不再使用七牛云。请确保在执行关闭操作之前,已经备份好相关的文件和数据,以免丢失重要信息。 ### 回答2: 要关闭FastAdmin中的七牛云服务,您可以按照以下步骤进行操作: 1. 登录FastAdmin后台管理系统。在网址后加上`/admin`,输入您的管理员账号和密码,然后点击登录按钮。 2. 进入FastAdmin管理后台后,在左侧菜单中找到并点击“系统”选项。 3. 在“系统”菜单下拉列表中选择“设置”选项,然后点击“附件设置”子选项。 4. 在“附件设置”页面中,您会找到一个名为“附件上传驱动”或“七牛云设置”的选项,具体名称可能会有所不同,但一般都会有直接或间接与七牛云相关的描述。 5. 找到并选择“本地存储”或“本地上传”等与七牛云设置相对应的选项。这将切换回本地文件存储,从而关闭七牛云。 6. 确认更改后,点击“保存”按钮以保存设置并关闭七牛云服务。 请注意,关闭FastAdmin中的七牛云服务可能会导致一些功能受限或无法使用,因为七牛云是一种云存储服务,用于存储和管理FastAdmin中的附件文件。但如果您不再需要使用七牛云,或者想要节省成本,关闭它可能是一个合理的选择。 ### 回答3: 要关闭FastAdmin七牛云的集成,可以按照以下步骤进行操作: 1. 登录FastAdmin后台管理系统,进入系统设置界面。 2. 在左侧菜单栏找到并点击「文件」或「存储设置」选项。 3. 在文件存储设置页面中,找到使用七牛云存储的相关选项。 4. 将相应的七牛云存储开关或配置相关的API信息清空或设为无效。具体操作方式可能根据FastAdmin版本的不同而有所差异。 5. 确认保存修改后,重新加载FastAdmin网站。 这样就成功关闭了FastAdmin七牛云的集成。关闭后,FastAdmin将不再使用七牛云存储服务,而是使用默认的本地存储功能。 如果遇到任何问题,建议参考FastAdmin官方文档或咨询相关技术支持人员。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦夏夜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值