ThinkPHP5上传图片至七牛云

1 下载官方PHP SDK

文档网址:https://developer.qiniu.com/kodo/sdk/1241/php#9

# 使用composer安装qiniu/php-sdk
# 安装sdk。安装即可使用
composer require qiniu/php-sdk

2 创建配置文件

位置app/extra/qiniu.php

return [
'ak' => '********************', // id
'sk' => '********************', // 秘钥
'bucket'=> '******', // 要上传的空间
'image_url' => '*************', // 空间域名
];

3 创建上传类

位置:app/common/Upload.php

<?php
namespace app\common;

use Qiniu\Auth; // 鉴权类
use Qiniu\Storage\UploadManager; // 上传类

/**
* Class Upload 图片上传到七牛云
*/
class Upload
{
public static function qiNiuUpload()
{

// 获取上传的图片
$file = request()->file('file');
// 图片存储在本地的临时路经
$filePath = $file->getRealPath();

// 获取图片后缀
$ext = pathinfo($file->getInfo('name'),PATHINFO_EXTENSION);
// 上传到七牛后保存的新图片名
$newImageName = date('Y').'/'.date('m').'/'.substr(md5($file->getInfo('name')),0,6).date('YmdHis').rand(000000,999999).'.'.$ext;

// 构建鉴权对象
$auth = new Auth(config('qiniu.ak') , config('qiniu.sk'));
// 要上传的空间
$token = $auth->uploadToken(config('qiniu.bucket'));

// 初始化 UploadManager 对象并进行文件的上传。
$uploadMgr = new UploadManager();
list($ret , $err) = $uploadMgr->putFile($token , $newImageName , $filePath);

if($err !== null){
return null;
}else{
// 图片上传成功
return $newImageName;
}
}
}

4 控制器使用

位置:app/admin/controller/Image.php

<?php
namespace app\admin\controller;

use think\Request;
use app\common\Upload as qiUpload;

/**
* Class Image 后台图片上传
* @package app\admin\controller
*/
class Image extends Base
{
/**
* 图片上传至七牛云
*/
public function qiUpload()
{
$img = qiUpload::qiNiuUpload();

if($img){
$data = [
'status' => 1,
'message' => 'OK',
'img_url' => config('qiniu.image_url') . '/' . $img,
];

return json($data);
}else{
return json(['status'=>0,'message'=>'上传失败']);
}
}


/**
* 图片上传至本地
*/
public function upload()
{
$file = Request::instance()->file('file');
$info = $file->move('uploads');
// 上传成功
if($info && $info->getPathname()){
$data = [
'status' => 1,
'message' => 'OK',
'img' => '/'. $info->getPathname(),
];
return json($data);
}

// 上传失败
return json(['status'=>0,'message'=>'上传失败']);
}

}


相关推荐

  • 生成图片

    from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageFilterdef create_image_with_text(size, color, text, font_path, font_size, text_color, shadow_color, output_path): """ Create a new image of specified size and color with centered text that has a border and shadow. :param size: A tuple con

  • 获取指定目录下的所有图片信息

    1 获取指定目录下的所有图片信息// 获取指定目录下的所有图片信息 public function getImagesInfo($directory) { $images = []; // 创建递归目录迭代器 $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); // 遍历目录中的每个文件 foreach (

  • Thinkphp各版本的PHP要求

    ThinkPHP 8.0:运行环境要求PHP8.0+,兼容PHP8.3ThinkPHP 6.1:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 6.0:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 5.1:运行环境要求PHP5.6+,兼容PHP8.0ThinkPHP 5.0:运行环境要求PHP5.4+,兼容PHP7.3