ConcurrentUploadPartSample.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <?php
  2. /**
  3. * Copyright 2019 Huawei Technologies Co.,Ltd.
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  5. * this file except in compliance with the License. You may obtain a copy of the
  6. * License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software distributed
  11. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. * specific language governing permissions and limitations under the License.
  14. *
  15. */
  16. /**
  17. * This sample demonstrates how to multipart upload an object concurrently
  18. * from OBS using the OBS SDK for PHP.
  19. */
  20. if (file_exists ( 'vendor/autoload.php' )) {
  21. require 'vendor/autoload.php';
  22. } else {
  23. require '../vendor/autoload.php'; // sample env
  24. }
  25. if (file_exists ( 'obs-autoloader.php' )) {
  26. require 'obs-autoloader.php';
  27. } else {
  28. require '../obs-autoloader.php'; // sample env
  29. }
  30. use Obs\ObsClient;
  31. use Obs\ObsException;
  32. $ak = '*** Provide your Access Key ***';
  33. $sk = '*** Provide your Secret Key ***';
  34. $endpoint = 'https://your-endpoint:443';
  35. $bucketName = 'my-obs-bucket-demo';
  36. $objectKey = 'my-obs-object-key-demo';
  37. /*
  38. * Constructs a obs client instance with your account for accessing OBS
  39. */
  40. $obsClient = ObsClient::factory ( [
  41. 'key' => $ak,
  42. 'secret' => $sk,
  43. 'endpoint' => $endpoint,
  44. 'socket_timeout' => 30,
  45. 'connect_timeout' => 10
  46. ] );
  47. try
  48. {
  49. /*
  50. * Create bucket
  51. */
  52. printf("Create a new bucket for demo\n\n");
  53. $obsClient -> createBucket(['Bucket' => $bucketName]);
  54. /*
  55. * Claim a upload id firstly
  56. */
  57. $resp = $obsClient -> initiateMultipartUpload(['Bucket' => $bucketName, 'Key' => $objectKey]);
  58. $uploadId = $resp['UploadId'];
  59. printf("Claiming a new upload id %s\n\n", $uploadId);
  60. $sampleFilePath = '/temp/test.txt'; //sample large file path
  61. // you can prepare a large file in you filesystem first
  62. createSampleFile($sampleFilePath);
  63. $partSize = 5 * 1024 * 1024;
  64. $fileLength = filesize($sampleFilePath);
  65. $partCount = $fileLength % $partSize === 0 ? intval($fileLength / $partSize) : intval($fileLength / $partSize) + 1;
  66. if($partCount > 10000){
  67. throw new \RuntimeException('Total parts count should not exceed 10000');
  68. }
  69. printf("Total parts count %d\n\n", $partCount);
  70. $parts = [];
  71. $promise = null;
  72. /*
  73. * Upload multiparts to your bucket
  74. */
  75. printf("Begin to upload multiparts to OBS from a file\n\n");
  76. for($i = 0; $i < $partCount; $i++){
  77. $offset = $i * $partSize;
  78. $currPartSize = ($i + 1 === $partCount) ? $fileLength - $offset : $partSize;
  79. $partNumber = $i + 1;
  80. $p = $obsClient -> uploadPartAsync([
  81. 'Bucket' => $bucketName,
  82. 'Key' => $objectKey,
  83. 'UploadId' => $uploadId,
  84. 'PartNumber' => $partNumber,
  85. 'SourceFile' => $sampleFilePath,
  86. 'Offset' => $offset,
  87. 'PartSize' => $currPartSize
  88. ], function($exception, $resp) use(&$parts, $partNumber) {
  89. $parts[] = ['PartNumber' => $partNumber, 'ETag' => $resp['ETag']];
  90. printf ( "Part#" . strval ( $partNumber ) . " done\n\n" );
  91. });
  92. if($promise === null){
  93. $promise = $p;
  94. }
  95. }
  96. /*
  97. * Waiting for all parts finished
  98. */
  99. $promise -> wait();
  100. usort($parts, function($a, $b){
  101. if($a['PartNumber'] === $b['PartNumber']){
  102. return 0;
  103. }
  104. return $a['PartNumber'] > $b['PartNumber'] ? 1 : -1;
  105. });
  106. /*
  107. * Verify whether all parts are finished
  108. */
  109. if(count($parts) !== $partCount){
  110. throw new \RuntimeException('Upload multiparts fail due to some parts are not finished yet');
  111. }
  112. printf("Succeed to complete multiparts into an object named %s\n\n", $objectKey);
  113. /*
  114. * View all parts uploaded recently
  115. */
  116. printf("Listing all parts......\n");
  117. $resp = $obsClient -> listParts(['Bucket' => $bucketName, 'Key' => $objectKey, 'UploadId' => $uploadId]);
  118. foreach ($resp['Parts'] as $part)
  119. {
  120. printf("\tPart#%d, ETag=%s\n", $part['PartNumber'], $part['ETag']);
  121. }
  122. printf("\n");
  123. /*
  124. * Complete to upload multiparts
  125. */
  126. $resp = $obsClient->completeMultipartUpload([
  127. 'Bucket' => $bucketName,
  128. 'Key' => $objectKey,
  129. 'UploadId' => $uploadId,
  130. 'Parts'=> $parts
  131. ]);
  132. // deleteTempFile($sampleFilePath);
  133. } catch ( ObsException $e ) {
  134. echo 'Response Code:' . $e->getStatusCode () . PHP_EOL;
  135. echo 'Error Message:' . $e->getExceptionMessage () . PHP_EOL;
  136. echo 'Error Code:' . $e->getExceptionCode () . PHP_EOL;
  137. echo 'Request ID:' . $e->getRequestId () . PHP_EOL;
  138. echo 'Exception Type:' . $e->getExceptionType () . PHP_EOL;
  139. } finally{
  140. $obsClient->close ();
  141. }
  142. function createSampleFile($filePath)
  143. {
  144. if(file_exists($filePath)){
  145. return;
  146. }
  147. $filePath = iconv('UTF-8', 'GBK', $filePath);
  148. if(is_string($filePath) && $filePath !== '')
  149. {
  150. $fp = null;
  151. $dir = dirname($filePath);
  152. try{
  153. if(!is_dir($dir))
  154. {
  155. mkdir($dir,0755,true);
  156. }
  157. if(($fp = fopen($filePath, 'w')))
  158. {
  159. for($i=0;$i< 1000000;$i++){
  160. fwrite($fp, uniqid() . "\n");
  161. fwrite($fp, uniqid() . "\n");
  162. if($i % 100 === 0){
  163. fflush($fp);
  164. }
  165. }
  166. }
  167. }finally{
  168. if($fp){
  169. fclose($fp);
  170. }
  171. }
  172. }
  173. }
  174. function deleteTempFile($sampleFilePath) {
  175. if(file_exists($sampleFilePath)){
  176. unlink($sampleFilePath);
  177. };
  178. }