襄阳网站制作公司分享:oss分片上传

常见问题     |      2020-10-20 | 阅读数:32次
 //$accessKeyId,$accessKeySecret这两个值都是可以在阿里云的账号中获取到的    //$endpoint是oss仓库中的 Endpoint地域节点中的外网访问的那个,也可以是传输加速域名的那个    //$bucket 是oss的仓库名称    //$object是指在上传到阿里云oss后文件的路径(其中包含了路径+文件名称)    //$filePath是指在前端上传文件到后端后,有一个临时存放的位置,一般的键名是tmp_name    
 public function ossvideo(){
    $name = input('name');
    $file = request()->file('imgfile');
    $arrList1 = $_FILES['imgfile']['name'];
    $arrList2 = $_FILES['imgfile']['tmp_name'];
    $object=$name.date('Y-m-d', time()) . '/'.$arrList1;

    $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, true);
    try {
        $uploadId = $ossClient->initiateMultipartUpload($this->bucket, $object);
    } catch (OssException $e) {
        return $e->getMessage();
    }
    /*
     * step 2. Upload parts
     */
    $partSize = 10 * 1024 * 1024;
    $uploadFile = $arrList2;
    $uploadFileSize = filesize($uploadFile);
    $pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
    $responseUploadPart = array();
    $uploadPosition = 0;
    $isCheckMd5 = true;
    foreach ($pieces as $i => $piece) {
        $fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
        $toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
        $upOptions = array(
            $ossClient::OSS_FILE_UPLOAD => $uploadFile,
            $ossClient::OSS_PART_NUM => ($i + 1),
            $ossClient::OSS_SEEK_TO => $fromPos,
            $ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
            $ossClient::OSS_CHECK_MD5 => $isCheckMd5,
        );
        if ($isCheckMd5) {
            $contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
            $upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
        }
        //2. Upload each part to OSS
        try {
            $responseUploadPart[] = $ossClient->uploadPart($this->bucket, $object, $uploadId, $upOptions);
        } catch (OssException $e) {

            return $e->getMessage();

        }

    }
    $uploadParts = array();
    foreach ($responseUploadPart as $i => $eTag) {
        $uploadParts[] = array(
            'PartNumber' => ($i + 1),
            'ETag' => $eTag,
        );

    }
    /**
     * step 3. Complete the upload
     */
    try {
        $info=$ossClient->completeMultipartUpload($this->bucket, $object, $uploadId, $uploadParts);

        $data=[
            'name'=>$name.date('Y-m-d', time()) . '/'.$arrList1,
            'size'=>$info['info']['speed_upload'],
            'tiem'=>$info['date']
        ];

        db('ossarchives')->insert($data);
        return json(['code'=>1,"msg"=>'上传完成']);
    } catch (OssException $e) {
        return $e->getMessage();
    }

}
襄阳网站制作公司分享:oss分片上传

移动端扫描浏览

网站优化、网站建设、APP开发、小程序开发