美文网首页
分块上传预签名Demo

分块上传预签名Demo

作者: lewzylu | 来源:发表于2018-05-07 14:54 被阅读0次

    分块上传预签名Demo

    • 以下是分块上传的两个步骤
    • 初始化分片上传
    • 获取上传分片的预签名URL
    • 使用该URL可以不带签名直接上传
    <?php
    
    require(__DIR__ . DIRECTORY_SEPARATOR . 'cos-autoloader.php');
    
    $cosClient = new Qcloud\Cos\Client(array('region' => getenv('COS_REGION'),
        'credentials'=> array(
            'secretId'    => '',
            'secretKey' => '')));
    
    //bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
    $bucket = 'lewzylu02-1252448703';
    $key = 'a.txt';
    $local_path = "E:/a.txt";
    $uploadId = "111";
    
    //初始化分块上传获取uploadId
    try {
        $result = $cosClient->createMultipartUpload(array(
            'Bucket' => $bucket,
            'Key' => $key,
        ));
        print_r($result);
        $uploadId = $result['UploadId'];
    } catch (\Exception $e) {
        echo "$e\n";
    }
    
    // 获取分块上传预签名
    try {
        #此处可以替换为其他上传接口
        $command = $cosClient->getCommand('uploadPart', array(
            'Bucket' => $bucket,
            'Key' => $key,
            'UploadId' => $uploadId,
            'PartNumber' => '1',
            'Body' => ''
        ));
        $signedUrl = $command->createPresignedUrl('+10 minutes');
        echo ($signedUrl);
    } catch (\Exception $e) {
        echo "$e\n";
    }
    
    • complete操作则需要获取到每一块的ETag
    • ETag需要从上传的response中获取
    # completeMultipartUpload接口
    $rt = $cosClient->completeMultipartUpload(array(
                'Bucket' => $bucket,
                'Key' => $key,
                'UploadId' => $uploadId,
                'Parts' => array(
            array(
                'ETag' => 'string',
                'PartNumber' => integer,
            ),
            // ... repeated
        )));
    
    • 若无法从分片的response中获取ETag,则可以调用ListParts接口,获取每一个成功上传的块的partNumber和Etag。
    # ListParts 接口
    try {
        $result = $cosClient->ListParts(array(
            'Bucket' => $bucket,
            'Key' => $key,
            'UploadId'=> $uploadId
        ));
        print_r($result);
    } catch (\Exception $e) {
        echo "$e\n";
    }
    

    相关文章

      网友评论

          本文标题:分块上传预签名Demo

          本文链接:https://www.haomeiwen.com/subject/kcmmrftx.html