常見問題

襄陽網(wǎng)站制作公司分享:oss分片上傳

常見問題

2534

字體:
 //$accessKeyId,$accessKeySecret這兩個值都是可以在阿里云的賬號中獲取到的    //$endpoint是oss倉庫中的 Endpoint地域節(jié)點中的外網(wǎng)訪問的那個,也可以是傳輸加速域名的那個    //$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();
    }

}

[聲明]原創(chuàng)不易,請轉(zhuǎn)發(fā)者備注下文章來源(hbsjsd.cn)【速建時代】。