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配置');

}

$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'=>'上传失败']);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值