当前位置:网站首页>laravel8 实现阿里云文件上传

laravel8 实现阿里云文件上传

2022-06-10 21:49:00 s_罐装冰块

阿里云官方文档

简单上传 (aliyun.com)icon-default.png?t=M4ADhttps://help.aliyun.com/document_detail/88473.html1.通过composer 来下载所需插件。

       下面的官方文档有我们需要的compser

composer require aliyuncs/oss-sdk-php

安装 (aliyun.com)icon-default.png?t=M4ADhttps://help.aliyun.com/document_detail/85580.html2.在后台控制器中写入文件上传的代码。

        下面的官方文档有我们需要的官方的上传代码示例

 //阿里云上传
    public function uploades(Request $request)
    {
        //获取图片值
        //接收文件上传的值
        $file = $request->file('image');
//        返回一个文件字符串
        $path = $file->getRealPath();

        $ext = $file->getClientOriginalExtension();

// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        $accessKeyId = "";
        $accessKeySecret = "";
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        $endpoint = "https://oss-cn-shanghai.aliyuncs.com";
// 填写Bucket名称,例如examplebucket。
        $bucket = "";
// 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        $object = rand(1111, 9999) . '.' . $ext;
// <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
        $filePath = $path;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch (OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
//        返回上传图片路径
        $imgUrl = "https://songphoto.oss-cn-shanghai.aliyuncs.com" . $object;
        return ['url' => $imgUrl];
        print(__FUNCTION__ . "OK" . "\n");

    }

简单上传 (aliyun.com)icon-default.png?t=M4ADhttps://help.aliyun.com/document_detail/88473.html

注:在我们使用阿里云上传的时候,需要安装认证证书。

原网站

版权声明
本文为[s_罐装冰块]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_59527682/article/details/125131605