首页> 实战笔录 >PHP开发笔记 >ThinkPHP ThinkPHP

TP6上传文件/图片到阿里云OSS

作者:小萝卜 2022-06-17 浏览 1875

简介tp6文件上传至阿里云oss

1.使用composer安装oss插件

 
composer require aliyuncs/oss-sdk-php


2.config文件夹filesystem.php文件加入配置

 
//阿里云配置
        'aliyun_oss' => [
            'accessKeyId'      => '',  //您的Access Key ID
            'accessKeySecret'  => '',  //您的Access Key Secret
            'endpoint'   => 'https://oss-cn-beijing.aliyuncs.com',  //阿里云oss 外网地址endpoint
            'bucket'     => '',  //Bucket名称
            'url'           => ''  // 访问的地址 (可不配置)
        ],


3.后端上传代码

 
<?php
// | Date (c) 2021-09-24
// +----------------------------------------------------------------------
// | Author: XIAOLONG <459623123@qq.com>
// +----------------------------------------------------------------------
// | Describe: 公用图片上传
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\Request;
use think\facade\Db;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\Filesystem;
use OSS\OssClient;
use OSS\Core\OssException;
class Upload extends Publics{


    //上传图片到阿里云Oss
    public function upload_img_oss()
    {
        $file = request()->file('images');  //input name=image
        //要上传文件的临时路径
        $filePath = $_FILES['images']['tmp_name'];
        //$type = $_FILES['images']['type'];
        $type = $file->extension(); 
        // 尝试执行
        try {
            $accessKeyId = Filesystem::getDiskConfig('aliyun_oss','accessKeyId');//去阿里云后台获取秘钥
            $accessKeySecret =  Filesystem::getDiskConfig('aliyun_oss','accessKeySecret');//去阿里云后台获取秘钥
            $endpoint =  Filesystem::getDiskConfig('aliyun_oss','endpoint');//你的阿里云OSS地址
            $bucket =  Filesystem::getDiskConfig('aliyun_oss','bucket');//你的阿里云OSS地址
            //实例化对象 将配置传入
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            //这里是有sha1加密 生成文件名 之后连接上后缀
            $fileName = sha1(date('YmdHis', time()) . uniqid()) . '.' . $type;
           //上传至阿里云的目录 为年+月/日的格式
            $pathName = date('Y-m/d') . '/' .$fileName;
            //执行阿里云上传 bucket名称,上传的目录,文件
            $result = $ossClient->uploadFile($bucket, $pathName, $filePath); 
        } catch (OssException $e) {
            return json(['code'=>0,'title'=>'上传失败','mess'=>$e->getMessage()]);
        }
        //将结果输出
        return json(['code'=>200,'title'=>'上传成功','mess'=>$result['info']['url']]);
    }

}

很赞哦! (5)

文章评论

    高端网站建设