一、首先开通阿里云oss
二、如果是阿里云非本账号下的域名管理需要先验证域名有效性txt解析,然后添加cname解析
composer下载扩展:
composer require aliyuncs/oss-sdk-php composer require topthink/think-image
前端:
<form action="{:url('up')}" method="post" enctype="multipart/form-data"> <input type="file" name="image" id=""/> <input type="submit" name="" id="" value="提交" /> </form>
后端:
use OSS\OssClient; use OSS\Core\OssException; use think\Image; //oss 测试 public function up(){ if(request()->isPost()){ //接收文件 $image = request()->file('image'); // halt($image); $resResult = Image::open($image); $accessKeyId = "LTAI5tGNsrhAhjSRoh4TSarz"; $accessKeySecret = "DDbHRbzPcuz3rF8IU9cADdJyRMaPzM"; // 填写您的地域,这里以以华东1(杭州)为例,填写为https://oss-cn-hangzhou.aliyuncs.com。 $endpoint = "https://oss-cn-hangzhou.aliyuncs.com/imgs/"; // 填写Bucket名称。 $bucket= "zhaotianhao"; // 上传后文件名称 $object = md5(time().rand(11111,99999)).'.'.$resResult->type(); $ossPath = "imgs/".$object; //$filePath = "/imgs".$image->getInfo()['tmp_name']; try{ $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint); // 这里保存结果打印 $ossClient->uploadFile($bucket, $ossPath, $image->getInfo()['tmp_name']); } catch(OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } echo '上传成功'; } return view(); }
参考文档:
https://help.aliyun.com/document_detail/31836.html#d33e111