头闻号

柳学耀(个体经营)

眼影|胭脂|唇膏|粉底|其他彩妆化学品

首页 > 新闻中心 > 科技常识:PHP上传文件到阿里云OSS,nginx代理访问
科技常识:PHP上传文件到阿里云OSS,nginx代理访问
发布时间:2024-10-07 01:27:48        浏览次数:3        返回列表

今天小编跟大家讲解下有关PHP上传文件到阿里云OSS,nginx代理访问 ,相信小伙伴们对这个话题应该有所关注吧,小编也收集到了有关PHP上传文件到阿里云OSS,nginx代理访问 的相关资料,希望小伙伴们看了有所帮助。

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() { } 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; } 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> <img src="http://www.aidi.net.cn/article/detial/1779/{$oss_url}{$img.shop_img}"/></div>

如此浏览器中html 即可访问加载 oss上图片资源。

来源:爱蒂网