1:新创一个桶名
2:下载SDK
3:
4:
php编辑器 终端运行
5:阿里云复制代码
6:获取秘钥和毽
7:
控制器书写代码:切记引入oss
namespac App\Http\Controllers\exam\exam20; use OSS\OssClient; use OSS\Core\OssException; use OSS\Core\OssUtil; class ExamController extends Controller { /** * * 大文件上传 */ public function bigUPload(Request $request) { $img = $request->file('img'); // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。 $accessKeyId = "LTAI5tMcno4eUrPEi5wtNai9"; $accessKeySecret = "aHx1G0CSH4Rt6s9lIYQEjjsfM6Fa3h"; // Endpoint以杭州为例,其它Region请按实际情况填写。 $endpoint = "http://oss-cn-shanghai.aliyuncs.com"; // 新创建的桶名 $bucket = "wangyue666"; // 临时文件名称 $object = "test.jpg"; // 要上传的文件 $uploadFile = $img->getPathname(); /** * 步骤1:初始化一个分片上传事件,获取uploadId。 */ try { $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint); //返回uploadId。uploadId是分片上传事件的唯一标识,您可以根据uploadId发起相关的操作,如取消分片上传、查询分片上传等。 $uploadId = $ossClient->initiateMultipartUpload($bucket, $object); } catch (OssException $e) { printf(__FUNCTION__ . ": initiateMultipartUpload FAILED\n"); printf($e->getMessage() . "\n"); return; } /* * 步骤2:上传分片。 */ $partSize = 10 * 1024 * 1024; $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, // 是否开启MD5校验,true为开启。 $ossClient::OSS_CHECK_MD5 => $isCheckMd5, ); // 开启MD5校验。 if ($isCheckMd5) { $contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos); $upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5; } try { // 上传分片。 $responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions); } catch (OssException $e) { printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n"); printf($e->getMessage() . "\n"); return; } } // $uploadParts是由每个分片的ETag和分片号(PartNumber)组成的数组。 $uploadParts = array(); foreach ($responseUploadPart as $i => $eTag) { $uploadParts[] = array( 'PartNumber' => ($i + 1), 'ETag' => $eTag, ); } /** * 步骤3:完成上传。 */ try { // 执行completeMultipartUpload操作时,需要提供所有有效的$uploadParts。OSS收到提交的$uploadParts后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。 $result = $ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts); } catch (OssException $e) { printf(__FUNCTION__ . ": completeMultipartUpload FAILED\n"); printf($e->getMessage() . "\n"); return; } $result = $result['oss-requestheaders']['Host']; // 获得文件上传的url路径 $resultUrl = $result . "/" . $object; } }
测试: