首页 > 其他分享 >fastadmin api 腾讯云upload上传图片

fastadmin api 腾讯云upload上传图片

时间:2024-01-24 11:55:47浏览次数:26  
标签:fastadmin request upload api attachment file post config

    /**
     * 腾讯云Cos上传文件
     * 上传分片
     * 合并分片
     * @param File $file 文件流
     */
    public function uploadCos()
    {
        if (!Auth::isModuleAllow()) {
            $this->error("请登录后再进行操作");
        }

        $config = get_addon_config('cos');
        $this->cosConfig = array(
            'region'      => $config['region'],
            'schema'      => 'https', //协议头部,默认为http
            'credentials' => array(
                'secretId'  => $config['secretId'],
                'secretKey' => $config['secretKey']
            )
        );
        $oss = new Client($this->cosConfig);

        //检测删除文件或附件
        $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
            //如果设定为不备份则删除文件和记录 或 强制删除
            if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
                if ($attachment && !empty($attachment['id'])) {
                    $attachment->delete();
                }
                if ($upload) {
                    //文件绝对路径
                    $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
                    @unlink($filePath);
                }
            }
        };

        $chunkid = $this->request->post("chunkid");

        if ($chunkid) {
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filesize = $this->request->post("filesize");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            $key = $this->request->post("key");
            $uploadId = $this->request->post("uploadId");

            if ($action == 'merge') {

                $attachment = null;
                $upload = null;
                //合并分片
                if ($config['uploadmode'] == 'server') {
                    //合并分片文件
                    try {
                        $upload = new Upload();
                        $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                }

                $etags = $this->request->post("etags/a", []);
                if (count($etags) != $chunkcount) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error("分片数据错误");
                }
                $listParts = [];
                for ($i = 0; $i < $chunkcount; $i++) {
                    $listParts[] = array("PartNumber" => $i + 1, "ETag" => $etags[$i]);
                }
                try {
                    $result = $oss->completeMultipartUpload(array(
                            'Bucket'   => $config['bucket'],
                            'Key'      => $key,
                            'UploadId' => $uploadId,
                            'Parts'    => $listParts
                        )
                    );
                } catch (\Exception $e) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error($e->getMessage());
                }

                if (!isset($result['Key'])) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error("上传失败");
                } else {
                    $checkDeleteFile($attachment, $upload);
                    $this->success("上传成功", '', ['url' => "/" . $key, 'fullurl' => cdnurl("/" . $key, true)]);
                }
            } else {

                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                try {
                    $params = array(
                        'Bucket'     => $config['bucket'],
                        'Key'        => $key,
                        'UploadId'   => $uploadId,
                        'PartNumber' => $chunkindex + 1,
                        'Body'       => $file->fread($file->getSize())
                    );
                    $ret = $oss->uploadPart($params);
                    $etag = $ret['ETag'];
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }

                $this->success("上传成功", "", [], 3, ['ETag' => $etag]);
            }
        } else {

            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            //文件绝对路径
            $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

            $url = $attachment->url;

            try {

                $ret = $oss->upload($config['bucket'], ltrim($attachment->url, "/"), $upload->getFile());


                //成功不做任何操作
            } catch (\Exception $e) {
                $checkDeleteFile($attachment, $upload, true);
                $this->error("上传失败" . $e->getMessage());
            }

            $checkDeleteFile($attachment, $upload);

            // 记录云存储记录
            $data = $attachment->toArray();
            unset($data['id']);
            $data['storage'] = 'cos';
            Attachment::create($data, true);

            $this->success("上传成功", ['url' => $url, 'fullurl' => cdnurl($url, true)]);
        }
        return;
    }

 

标签:fastadmin,request,upload,api,attachment,file,post,config
From: https://www.cnblogs.com/web928943/p/17984350

相关文章

  • 强大的Stream API
    StreamAPI说明 Java8中有两大最为重要的改变。第一个是Lambda表达式;另外一个则是StreamAPI。 StreamAPI(java.util.stream)把真正的函数式编程风格引入到Java中。这是目前为止对Java类库最好的补充,因为StreamAPI可以极大提供Java程序员的生产力,让程序员写出高效率......
  • 梳理Langchain-Chatchat知识库API接口
    一.Langchain-Chatchat知识库管理1.Langchain-Chatchat对话和知识库管理界面  Langchain-Chatchatv0.28完整的界面截图,如下所示:2.知识库中源文件和向量库  知识库test中源文件和向量库的位置,如下所示:3.知识库表结构  knowledge_base数据表内容,如下所示:二.......
  • Microsoft 365 开发:开发者如何使用Delegated Access通过PowerShell调用Graph API
    51CTOBlog地址:https://blog.51cto.com/u_13969817MicrosoftGraphAPI是一种RESTfulwebAPI,它整合了对各种Microsoft365服务的访问,允许开发人员创建跨多个平台与数据交互的应用程序,包括AzureActiveDirectory、SharePoint、OneDrive、Outlook等。MicrosoftGraphPowerShell适......
  • Microsoft 365 开发:开发者如何使用App ID连接Graph API的方法汇总
    51CTOBlog地址:https://blog.51cto.com/u_13969817在上文中我们介绍了如何在AzureAD中注册Application并授权相关GraphAPI,本文将给大家介绍开发者如何使用AppID和Certificate(Secret)通过PowerShell连接GraphAPI?采用AppID和Certificate通过PowerShell连接GraphAPI的命令如下所......
  • Microsoft 365:如何在Azure AD中注册Application并授权相关Graph API
    51CTOBlog地址:https://blog.51cto.com/u_13969817在使用Powershell连接GraphAPI之前,首先管理员要在AzureAD中新建Application,并授权APIPermission和Credentials,本文将给大家做细节介绍:·      在AzureAD中注册Application·      授权GraphAPIPermission· ......
  • APIO2014 回文串
    APIO2014回文串decription给定一个长度为\(n\)的字符串\(S\)。求其所有回文子串中出现次数乘上长度的最大值。\(n\leq3\times10^5\)solution根据经典结论,长度为\(n\)的字符串的本质不同回文子串个数不超过\(n\)个,我们可以找出所有本质不同回文子串,然后计算它们的......
  • API调试?试试Apipost
    你是否经常遇到接口开发过程中的各种问题?或许你曾为接口测试与调试的繁琐流程而烦恼。不要担心!今天我将向大家介绍一款功能强大、易于上手的接口测试工具——Apipost,并带你深入了解如何玩转它,轻松实现接口测试与调试。什么是Apipost?Apipost是一款API全生命周期管理平台,它提供了一系......
  • IDEA插件推荐:Apipost-Helper,免费!
    IDEA插件市场中的API调试插件不是收费(FastRequest)就是不好用(apidoc、apidocx等等)今天给大家介绍一款国产的API调试插件:Apipost-Helper,完全免费且好看好用!这款插件由Apipost团队开发的,其官方介绍是:用于IDEA项目快速生成API文档,快速查询接口、接口代码功能,并支持在IDEA中进行API调......
  • IDEA插件推荐:Apipost-Helper,免费!
    IDEA插件市场中的API调试插件不是收费(FastRequest)就是不好用(apidoc、apidocx等等)今天给大家介绍一款国产的API调试插件:Apipost-Helper,完全免费且好看好用!这款插件由Apipost团队开发的,其官方介绍是:用于IDEA项目快速生成API文档,快速查询接口、接口代码功能,并支持在IDEA中进行API......
  • API调试?试试Apipost
    你是否经常遇到接口开发过程中的各种问题?或许你曾为接口测试与调试的繁琐流程而烦恼。不要担心!今天我将向大家介绍一款功能强大、易于上手的接口测试工具——Apipost,并带你深入了解如何玩转它,轻松实现接口测试与调试。什么是Apipost?Apipost是一款API全生命周期管理平台,它提供了......