base64格式图片上传至阿里云OSS|base64格式图片上传至阿里云OSS --- 2019-07-18

namespace Admin\Controller;
use think\Controller;
use Admin\Controller\OssStorageController;
class PictureUploadController extends Controller {
private $Bucket;
private $endpoint;
private $url_prefix ;
public function _initialize()
{
//获取oss配置
$oss_config = M('oss_config')->where('id=1')->find();
if (empty($oss_config)) {
error('未找到oss配置');
}
【base64格式图片上传至阿里云OSS|base64格式图片上传至阿里云OSS --- 2019-07-18】$this->Bucket = $oss_config['bucket'];
$this->endpoint = $oss_config['endpoint'];
//获取oss地址前缀 默认使用bjy
$this->url_prefix = 'https://' . $this->Bucket . '.' . $oss_config['endpoint'] . '/';
}
/** 封装阿里云OSS上传的方法
* Created by PhpStorm.
* User: weiyuntao
* Date: 2019/7/18 0007
* Time: 上午 16:10
*/
function uploadImage($dst, $getFile)
{
#配置OSS基本配置
$config = array(
'KeyId' => 'LTAIUejVxNYfjCWq',//你的KeyId
'KeySecret' => 'JR0G7dP5axfhKldw6xIXw95J0H7mIt',//你的KeySecret
'Endpoint' => $this->endpoint,//你的Endpoint
'Bucket' => $this->Bucket,//你的Bucket
);
$ossClient = new OssClient($config['KeyId'], $config['KeySecret'],$config['Endpoint']);
#执行阿里云上传
$result = $ossClient->uploadFile($config['Bucket'], $dst, $getFile);
#返回
return $result;
}
/** $imgBase64 图片base64格式
* Created by PhpStorm.
* User: weiyuntao
* Date: 2019/7/18 0007
* Time: 上午 16:10
*/
public function imageDoAliyunOss()
{
$imgBase64 = I('POST.imgBase64');
if(empty($imgBase64)){
error('图片信息传递为空');
}
#引用阿里云上传文件
$oss_storage = new OssStorageController($this->Bucket);
$push = [];
foreach($imgBase64 as $key=>$value) {
#转化base64编码图片
if (preg_match('/^(data:\s*image\/(\w+); base64,)/', $value, $res)) {
//获取图片类型 png jpg等
$type = $res[2];
//图片名字
$fileName = md5(microtime()) .mt_rand(1,10000). '.' . $type;
// 临时文件
$tmpfname = tempnam("/image/", "FOO");
//保存图片
$handle = fopen($tmpfname, "w");
//阿里云oss上传的文件目录
$dst = 'zxnew/';
if (fwrite($handle, base64_decode(str_replace($res[1], '', $value)))) {
#上传图片至阿里云OSS
$url = $oss_storage->uploadFile($dst . $fileName, $tmpfname);
#关闭缓存
fclose($handle);
#删除本地该图片
unlink($tmpfname);
$returnUrl = 'https://' . $this->Bucket . '.' . $this->endpoint . '/' . $dst . $fileName;
array_push($push, $returnUrl);
unset($res); //清除
} else {
continue;
}
}
}
//返回图片链接
if($push){
echo json_encode(['code'=>200,'status'=>1,'msg'=>'上传成功','data'=>$push]);
}else{
echo json_encode(['code'=>200,'status'=>0,'msg'=>'上传失败']);
}
}
}

    推荐阅读