thinkphp5.1

编程入门 行业动态 更新时间:2024-10-10 00:28:09

thinkphp5.1

thinkphp5.1

composter下载扩展:

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

本文发布于:2024-02-07 00:48:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1751762.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!