php tp5上传图片到阿里云OSS

1.登录阿里云OSS管理控制台创建Bucket
php tp5上传图片到阿里云OSS_第1张图片
(写入名称,这个我已经创建过了,我接下来会用到,注意Endpoint,后面会用到)
php tp5上传图片到阿里云OSS_第2张图片
为了方便管理图片,可以在Bucket多建目录进行存放:
php tp5上传图片到阿里云OSS_第3张图片
2.在tp5的config中做以下配置

	//阿里云OSS配置
	'alioss'     =>[
	    'KeyId'      => 'LTAI4Frk39sKAiJe3sRSKg4w',  //AccessKey ID
	    'KeySecret'  => 'nV2XfBuTEFUUYfT2gHnFMUAgwwCinQ',  //Access Key Secret
	    'EndPoint'   => 'oss-cn-beijing.aliyuncs.com',  //外网访问节点
	    'Bucket'     => 'lten',  //Bucket名称
	],

AccessKey ID和 Access Key Secret可以在这里查看
php tp5上传图片到阿里云OSS_第4张图片
php tp5上传图片到阿里云OSS_第5张图片
3.到阿里云对象存储OSS官网文档,下载PHP的demo,下载后解压重命名文件夹为aliyun-oss,我放到了tp5的extend目录下面:
php tp5上传图片到阿里云OSS_第6张图片
4.我定义了一个Common类,里面有上传图片的方法

	use \think\Controller;
	use think\Image;
	require_once APP_PATH . '/../extend/aliyun-oss/autoload.php';
	use OSS\Core\OssException;
	use OSS\OssClient;
	class Common extends Controller
	{
		/**
	     *上传图片的接口
	     */
	    public function uploadtest(){
	        $file = request()->file('file');
	        $res = [];
	        if($file){
	            $res = self::uploadFile('banner',$file);
	            if($res['code']==200){
	                //图片完整地址
	                $headimg = $res['data'];
	                //业务逻辑省略......
	            }else{
	                return $this->error('上传失败');
	            }
	            return json($res);
	        }
	    }
	    //上传图片到阿里云
	    public static function uploadFile($mulu,$file) {
	        $resResult = Image::open($file);
	        try {
	            $KeyId = config('alioss.KeyId');
	            $KeySecret = config('alioss.KeySecret');
	            $EndPoint = config('alioss.EndPoint');
	            $Bucket = config('alioss.Bucket');
	            //实例化
	            $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
	            //sha1加密 生成文件名 连接后缀
	            $fileName = $mulu.'/'.sha1(date('YmdHis', time()) . uniqid()) . '.' . $resResult->type();
	            //执行阿里云上传
	            $result = $ossClient->uploadFile($Bucket, $fileName, $file->getInfo()['tmp_name']);
	            //图片地址:$result['info']['url']
	            $arr = ['code'=>200,'msg'=>'上传成功','data'=>$result['info']['url']];
	        } catch (OssException $e) {
	            $arr = ['code'=>0,'msg'=>$e->getMessage(),'data'=>''];
	        }
	        return $arr;
	    }
	}

5.前台

<div class="layui-upload" id="upload-thumb">
    <label class="layui-form-label">缩略图</label>
    <button type="button" class="layui-btn" id="thumb">上传图片</button>
    <div class="layui-upload-list">
        <label class="layui-form-label"></label>
        <img class="layui-upload-img" id="demo1" width="150" height="150" {notempty name="$article.thumb"}src="{$article.thumb}"{/notempty}>{notempty name="$article.thumb"}<input type="hidden" name="thumb" value="{$article.thumb}">{/notempty}
        <p id="demoText"></p>
    </div>
</div>
//上传图片接口
 layui.use('upload', function(){
     var upload = layui.upload;
     //执行实例
     var uploadInst = upload.render({
         elem: '#thumb' //绑定元素
         ,url: "{:url('common/uploadtest')}" //上传接口
         ,data:{use:'article_thumb'}
         ,done: function(res){
             //上传完毕回调
             if(res.code == 200) {
                 //前台显示预览图
                 $('#demo1').attr('src',res.data);
                 $('#upload-thumb').append('+ res.data +'">');
             } else {
                 layer.msg(res.msg);
             }
         }
         ,error: function(){
             //请求异常回调
             //演示失败状态,并实现重传
             var demoText = $('#demoText');
             demoText.html('上传失败 重试');
             demoText.find('.demo-reload').on('click', function(){
                 uploadInst.upload();
             });
         }
     });
 });

你可能感兴趣的:(php,javascript)