当前位置: 首页 > news >正文

fastadmin 文件上传七牛云

1-安装七牛云官方SDK

composer require qiniu/php-sdk

2-七牛云配置

<?phpnamespace 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 {//返回图片的完整URLDb::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 方法

<?phpnamespace 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方法

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • PCL-半径滤波
  • 基于深度学习的创新设计的生成AI
  • vue+ThreeJS:从0 到1 搭建开发环境
  • 一些深度学习相关指令
  • 【C-实践】文件服务器(1.0)
  • 【代码随想录训练营第42期 Day53打卡 - 图论Part4 - 卡码网 110. 字符串接龙 105. 有向图的完全可达性
  • 10分钟教你使用docker在本地部署Wordpress
  • 【C++进阶】hash表的封装
  • 芯旺微,车规级32位MCU KF32A芯片简介
  • MATLAB中sim函数的用法
  • JavaWeb后端开发总结(3)
  • 微知-BIOS中的XHCI模式是什么意思?(usb3.0的扩展控制器影响usb3.0速率等选项)
  • Android之同一个Thread线程里只能有一个Looper?(ThreadLocal)
  • 计算机毕业设计 大学志愿填报系统 Java+SpringBoot+Vue 前后端分离 文档报告 代码讲解 安装调试
  • 前端面试八股文
  • android 一些 utils
  • Android系统模拟器绘制实现概述
  • const let
  • docker-consul
  • ES6核心特性
  • Javascript弹出层-初探
  • Laravel5.4 Queues队列学习
  • LintCode 31. partitionArray 数组划分
  • log4j2输出到kafka
  • Object.assign方法不能实现深复制
  • 阿里云应用高可用服务公测发布
  • 初探 Vue 生命周期和钩子函数
  • 大快搜索数据爬虫技术实例安装教学篇
  • 快速体验 Sentinel 集群限流功能,只需简单几步
  • 通过npm或yarn自动生成vue组件
  • 一起参Ember.js讨论、问答社区。
  • 阿里云移动端播放器高级功能介绍
  • 宾利慕尚创始人典藏版国内首秀,2025年前实现全系车型电动化 | 2019上海车展 ...
  • 直播平台建设千万不要忘记流媒体服务器的存在 ...
  • ​LeetCode解法汇总1276. 不浪费原料的汉堡制作方案
  • ![CDATA[ ]] 是什么东东
  • #### go map 底层结构 ####
  • (02)Hive SQL编译成MapReduce任务的过程
  • (06)Hive——正则表达式
  • (android 地图实战开发)3 在地图上显示当前位置和自定义银行位置
  • (pytorch进阶之路)CLIP模型 实现图像多模态检索任务
  • (SpringBoot)第七章:SpringBoot日志文件
  • (附源码)springboot宠物管理系统 毕业设计 121654
  • (黑客游戏)HackTheGame1.21 过关攻略
  • (转) Android中ViewStub组件使用
  • (转载)虚函数剖析
  • ****** 二十三 ******、软设笔记【数据库】-数据操作-常用关系操作、关系运算
  • .htaccess配置常用技巧
  • .net Application的目录
  • .Net core 6.0 升8.0
  • .NET Core WebAPI中使用Log4net 日志级别分类并记录到数据库
  • .NET MAUI Sqlite程序应用-数据库配置(一)
  • .Net Web窗口页属性
  • .NET性能优化(文摘)
  • .vimrc 配置项