fastadmin 文件上传七牛云

2024-09-06 00:20
文章标签 上传 fastadmin 七牛云

本文主要是介绍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方法


                                    

这篇关于fastadmin 文件上传七牛云的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1140474

相关文章

Spring MVC 图片上传

引入需要的包 <dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-

在SSH的基础上使用jquery.uploadify.js上传文件

在SSH框架的基础上,使用jquery.uploadify.js实现文件的上传,之前搞了好几天,都上传不了, 在Action那边File接收到的总是为null, 为了这个还上网搜了好多相关的信息,但都不行,最后还是搜到一篇文章帮助到我了,希望能帮助到为之困扰的人。 jsp页面的关键代码: <link rel="stylesheet" type="text/css" href="${page

【CTF Web】BUUCTF Upload-Labs-Linux Pass-13 Writeup(文件上传+PHP+文件包含漏洞+PNG图片马)

Upload-Labs-Linux 1 点击部署靶机。 简介 upload-labs是一个使用php语言编写的,专门收集渗透测试和CTF中遇到的各种上传漏洞的靶场。旨在帮助大家对上传漏洞有一个全面的了解。目前一共20关,每一关都包含着不同上传方式。 注意 1.每一关没有固定的通关方法,大家不要自限思维! 2.本项目提供的writeup只是起一个参考作用,希望大家可以分享出自己的通关思路

Vue3上传图片报错:Current request is not a multipart request

当你看到错误 "Current request is not a multipart request" 时,这通常意味着你的服务器或后端代码期望接收一个 multipart/form-data 类型的请求,但实际上并没有收到这样的请求。在使用 <el-upload> 组件时,如果你已经设置了 http-request 属性来自定义上传行为,并且遇到了这个错误,可能是因为你在发送请求时没有正确地设置

OpenStack:Glance共享与上传、Nova操作选项解释、Cinder操作技巧

目录 Glance member task Nova lock shelve rescue Cinder manage local-attach transfer backup-export 总结 原作者:int32bit,参考内容 从2013年开始折腾OpenStack也有好几年的时间了。在使用过程中,我发现有很多很有用的操作,但是却很少被提及。这里我暂不直接

使用http-request 属性替代action绑定上传URL

在 Element UI 的 <el-upload> 组件中,如果你需要为上传的 HTTP 请求添加自定义的请求头(例如,为了通过身份验证或满足服务器端的特定要求),你不能直接在 <el-upload> 组件的属性中设置这些请求头。但是,你可以通过 http-request 属性来自定义上传的行为,包括设置请求头。 http-request 属性允许你完全控制上传的行为,包括如何构建请求、发送请

Vue3图片上传报错:Required part ‘file‘ is not present.

错误 "Required part 'file' is not present" 通常表明服务器期望在接收到的 multipart/form-data 请求中找到一个名为 file 的部分(即文件字段),但实际上没有找到。这可能是因为以下几个原因: 请求体构建不正确:在发送请求时,可能没有正确地将文件添加到 FormData 对象中,或者使用了错误的字段名。 前端代码错误:在前端代码中,可能

【SpringMVC学习06】SpringMVC中实现文件上传

1. 环境准备 springmvc上传文件的功能需要两个jar包的支持,如下 2. 单个文件的上传 2.1 前台页面 简单的写一下前台页面,注意一点的是form表单中别忘了写enctype=”multipart/form-data”属性: <tr><td>商品图片</td><td><c:if test="${itemsCustom.pic !=null}"><img src="/f

使用Vant Uploader 文件上传,后端java中MultipartFile接收不到文件问题解决

问题 在Uploader组件 after-read回调函数将获取的file对象上传到服务器。 <van-uploader:after-read="uploadFile"/>uploadFile(file) {const data = new FormData();data.

git命令上传代码到gitHub、gitLab

1 、输入git账号和密码 git config --global user.name"git账号" git config --global user.name"密码" 2.添加要上传的SSH (如果你的文件已经有了SSH,删除本身有的)git remote rm origin 添加 git remote add origin SSH或http 3 添加本地的所有文件  git ad