本文主要是介绍thinkphp5.1 || 上传图片到阿里云oss,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
composter下载扩展:
https://packagist.org/packages/aliyuncs/oss-sdk-php
composer require aliyuncs/oss-sdk-php
composer require topthink/think-image
配置config:
在application同级目录的config目录里面新建一个aliyun_oss.php的文件,如下:
<?php
/*** Created by PhpStorm.* User: Administrator* Date: 2021/12/8* Time: 11:25*/// +----------------------------------------------------------------------
// | 阿里云OSS配置
// +----------------------------------------------------------------------
return ['KeyId' => '', //Access Key ID'KeySecret' => '', //Access Key Secret'Endpoint' => '', //阿里云oss 外网地址endpoint'Bucket' => '', //Bucket名称
];
前端:up_image.html
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head>
<body>
<form method="post" enctype="multipart/form-data"><input type="file" name="file"><input type="submit" value="提交">
</form>
</body>
</html>
后端:up_image.php
<?phpnamespace app\index\controller;use app\api\controller\Base;
use OSS\OssClient;
use think\Controller;
use think\facade\Config;
use think\Image;
use OSS\Core\OssException;class Uploadoss extends Controller
{public function up_image(){/*** 看到有很多人在上传的 时候现实移动到本地文件,然后上传到阿里云*大家都知道磁盘IO吧(I是input 输入) O(output 输出)*大量的删除文件写入文件对服务器也是有影响的*/if ($this->request->method() == 'POST') {$file = request()->file('file'); //获取到上传的文件$resResult = Image::open($file); //获取打开图片的信息,包括图像大小、类型等// 尝试执行try {$config = Config::pull('aliyun_oss'); //获取Oss的配置//实例化对象 将配置传入$ossClient = new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);//这里是有sha1加密 生成文件名 之后连接上后缀$fileName = sha1(date('YmdHis', time()) . uniqid()) . '.' . $resResult->type();//执行阿里云上传$result = $ossClient->uploadFile($config['Bucket'], $fileName, $file->getInfo()['tmp_name']);/*** 这个只是为了展示* 可以删除或者保留下做后面的操作*/$arr = ['图片地址:' => $result['info']['url'],'数据库保存名称' => $fileName];} catch (OssException $e) {return $e->getMessage();}//将结果输出dump($arr);}return $this->fetch();}
}
这篇关于thinkphp5.1 || 上传图片到阿里云oss的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!