thinkphp 七牛存储单文件、多文件上传,简化配置
程序员文章站
2022-05-26 22:30:27
...
简化使用七牛云存储实现文件上传功能
/**
* 上传七牛
*
* @author huqitao
*/
namespace Common\Utility;
class UploadImg {
protected $config;
protected $domain;
protected $bucket;
public function __construct($domain, $bucket) {
$this->domain = $domain;
$this->bucket = $bucket;
$this->config = array(
'maxSize' => 2 * 1024 * 1024, //文件大小
'rootPath' => './',
'saveName' => array('uniqid', ''),
'driver' => 'Qiniu',
'driverConfig' => array(
'secretKey' => '######', //七牛空间配置参数
'accessKey' => '########',
'domain' => $this->domain, //空间地址
'bucket' => $this->bucket, //空间名称
)
);
}
/**
* 上传一个文件
* @param array $file 文件参数
* @return array 返回 code 与文件路径或错误信息
*/
public function uploadOne($file) {
$upload = new \Think\Upload($this->config);
$info = $upload->uploadOne($file);
if (!$info) {
return [550, $upload->getError()];
}
return [200, $info['url']];
}
/**
* 上传多图
* @param type $files
* @return array 返回 code 与文件路径数组 或错误信息
*/
public function uploads($files) {
$upload = new \Think\Upload($this->config);
$info = $upload->upload($files);
if (!$info) {
return [550, $upload->getError()];
}
foreach ($info as $v) {
$pArray[] = "http://".$this->domain."/".strtr($v['name'], '/', '_');
}
return [200, $pArray];
}
}
使用方法,单图上传:public function uploadSchool() {
if (IS_POST) {
$domain = "#####";
$bucket = "###";
if (empty($_FILES)) {
$this->ajaxReturn(makeinformation(550, "没有上传图片"));
}
$uploadImg = new \Common\Utility\UploadImg($domain, $bucket);
$data = $uploadImg->uploadOne($_FILES['file']);
if ($data[0] != 200) {
$this->ajaxReturn(makeinformation(550, $data[1]));//失败返回错误
}
$this->ajaxReturn(makeinformation(200, '', array('url' => $data[1]))); //成功返回图片绝对地址
}
}
AD:真正免费,域名+虚机+企业邮箱=0元
上一篇: C程序-PAT-1026 程序运行时间