php实现上传文件到阿里云oss的方法:
1. 阿里云oss创建存储空间bucket(读写权限为:公共读)
2. 拿到相关配置
accesskeyid:*********accesskeysecret:*********endpoint:********bucket:********
3.创建 oss.php 上传类 (基于thinkphp5)
<?phpnamespace app\controller;use oss\ossclient;class oss { private static $_instance; private function __construct() { } private function __clone() { } /** * 获取一个ossclient实例 * @return null|ossclient */ public static function getinstance() { if (!(self::$_instance instanceof ossclient)) { try { self::$_instance = new ossclient(env('oss.access_key_id'), env('oss.access_key_secret'), env('oss.endpoint'), false); } catch (ossexception $e) { printf(__function__ . "creating ossclient instance: failed\n"); printf($e->getmessage() . "\n"); return null; } } return self::$_instance; } /** * 获取bucket * @return string */ public static function getbucketname() { return env('oss.bucket'); }}
3.上传调用
use app\controller\oss;...public function addshopimg(){ $this->checkparams('shop_id'); $file = $this->request->file('image'); if ($file && ($file->geterror() == '') && $file->checkimg() && $file->checksize(5*1024*1024)) { $info = $file->move(app_path . '../public/upload/shops/'); //上传图片至阿里云oss $filename = 'biz_oss/upload/shops/' . $info->getfilename(); $ossclient = oss::getinstance(); $bucket = oss::getbucketname(); $ossclient->uploadfile($bucket, $filename, $info->getpathname()); $data['shop_img'] = '/upload/shops/'.$info->getfilename(); $data['shop_id'] = $this->params['shop_id']; $re = db('shopimg')->insert($data); if($re){ api::output(); }else{ api::fail(2, '上传失败'); } } else { api::fail(1, '图片不合规'); } }
4.访问 oss域名地址 不可在浏览器直接访问 可用nginx 代理
配置中加入:
location ^~ /biz_oss {proxy_pass http://xxxxxx.oss-cn-shenzhen-internal.aliyuncs.com;}
重启nginx
nginx配置的域名(server_name)后接上 /biz_oss 如:kwdst.3ce.com/biz_oss 即可指向oss上资源存储的空间
如下 $oss_url = kwdst.3ce.com/biz_oss
<div style="text-align:center; width:100%; height:100%;"> <img src="{$oss_url}{$img.shop_img}" style="vertical-align:middle;" /></div>
如此浏览器中html 即可访问加载 oss上图片资源。
更多相关技术文章,请访问!