File management
Upload files
In BOS, the basic data unit for user operations is an object. An object consists of a key, metadata, and data. The key is the object’s name, the metadata provides a user-defined description as a set of name-value pairs, and the data is the content of the object.
The BOS PHP SDK provides a rich set of file upload APIs, and files can be uploaded in the following ways:
- Simple upload
- Append upload
- Multipart upload
- Large file upload
- Resumable upload
Simple upload
In simple upload scenarios, BOS supports uploading objects in the form of specified files, data streams, binary strings, and strings. Please refer to the following code:
1// Upload an object in the form of a data stream
2$string = "myobjectcontent";
3$length = Strlen($string);
4$md5 = base64_encode(md5($string,true));
5$data = file_get_contents("myfile","rb");
6$client->putObject($bucketName, $objectKey, $data, $length, $md5);
7 // Upload object from a string
8$client->putObjectFromString($bucketName, $objectKey, $string);
9 // Upload object directly from a file
10$client->putObjectFromFile($bucketName, $objectKey, $fileName);
Files are uploaded to BOS as objects. The APIs related to putObject support uploading objects no larger than 5 GB. Once the PutObject request is successfully processed, BOS will return the object's ETag in the Header as its unique identifier.
Set file meta information
Object metadata refers to the attributes of files provided by users when uploading to BOS. It is mainly divided into two categories: standard HTTP attribute settings (HTTP headers) and user-defined metadata.
Set Http header of object
The BOS PHP SDK essentially invokes the backend HTTP API, allowing users to customize the HTTP header of the object during upload. Descriptions of commonly used HTTP headers are as follows:
| Name | Description | Default value |
|---|---|---|
| Content-MD5 | File data verification: After setting, BOS will enable file content MD5 verification, compare the MD5 you provide with the MD5 of the file, and throw an error if they are inconsistent | None |
| Content-Type | File MIME Type: Specifies the file type and webpage encoding, determining the form and encoding used by browsers to read the file. If not explicitly set, BOS automatically generates it based on the file's extension. If the file has no extension, a default value is used. | application/octet-stream |
| Content-Disposition | Indicate the format in which the response content shall be displayed: either inline (i.e., as part of a Website or page) or as an attachment with a filename to be downloaded and saved locally | None |
| Content-Length | The length of the uploaded file. If it exceeds the length of the stream/file, it will be truncated; if it is insufficient, it will be the actual value | Stream/file duration |
| Expires | Cache expiration time | None |
| Cache-Control | Specify the caching behavior of the web page when the object is downloaded | no-cache: Do not use cache directly, but first go to the server to verify whether the object has been updated. If the object has been updated, the cache has expired, and the object needs to be re-downloaded from the server; otherwise, the cache is still valid, and the local cache will be used at this time. no-store: All content will not be cached. public: All content will be cached. private: All content will only be cached on the client. max-age=: The relative expiration time of cached content (in s). This option is only available in HTTP 1.1. Default: None |
Reference code is as follows:
1$options = array(
2 BosOptions::CONTENT_TYPE=>"text/plain",
3 BosOptions::CONTENT_MD5=>"md5",
4 BosOptions::CONTENT_LENGTH=>10,
5 BosOptions::CACHE_CONTROL=>" max-age=86400",
6 );
7$client->putObject($bucketName, $objectKey, $data, $options);
User-defined meta information
BOS supports user-defined metadata for describing objects. Example usage is shown in the following code:
1$user_meta = array("x-bce-meta-key1" => "value1");
2$client->putObject($bucketName,
3 $objectKey,
4 $data,
5 array(
6 'userMetadata' => $user_meta,
7));
Prompt:
- In the above code, the user has customized a metadata with the name "x-bce-meta-key1" and value "value1".
- When users download this object, this metadata can also be obtained.
- An object may have multiple similar parameters, but the total size of all user meta must not exceed 2KB.
Set storage class when uploading an object
BOS supports standard storage, infrequent access storage, and cold storage. Uploading an object and storing it as an infrequent access storage class is achieved by specifying the StorageClass. The parameters corresponding to the three storage classes are as follows:
| Storage class | Parameters |
|---|---|
| Standard storage | STANDARD |
| Infrequent access storage | STANDARD_IA |
| Cold storage | COLD |
Taking infrequent access storage as an example, the code is as follows:
1use BaiduBce\Services\Bos\StorageClass;
2 // After setting the object’s storage class to `StorageClass::STANDARD_IA`, an infrequent access object will be uploaded (defaulting to a standard object)
3$options = array(
4 BosOptions::STORAGE_CLASS => StorageClass::STANDARD_IA,
5);
6$response = $bos_client->putObjectFromString($bucket, $object, "test", $options);
After the putObject request is successfully processed, BOS returns the content-MD5 of the object in the header, which users can use to verify the file.
Append upload
Objects created using the simple upload method described above are all of a standard type and do not support append writes. This limitation can be inconvenient in scenarios where frequent data overwriting occurs, such as log files, video surveillance, and live video streaming.
To address this, Baidu AI Cloud Object Storage (BOS) specifically supports the AppendObject method, which allows files to be uploaded in an append-write fashion. Objects created through the AppendObject operation are categorized as Appendable Objects, enabling data to be appended to them. The size limit for AppendObject files is 0–5 GB.
Example code for uploading via AppendObject is as follows:
1// Upload an appendable object from a file
2file_put_contents($filename, "test of put append object");
3$response = $client->appendObjectFromFile($bucket, $appendKey, $filename, 0);
4 // Position for the next append write
5$nextOffset = $response->metadata[BosOptions::NEXT_APPEND_OFFSET];
6 // Upload an appendable object from a string
7$response = $client->appendObjectFromString($bucket, $appendKey, "appendStr", intval($nextOffset));
Multipart upload
Besides uploading files to BOS using simple upload and append upload methods, BOS also offers another upload method called Multipart Upload. This mode can be used in the following scenarios (but is not limited to these):
- When resumable uploads are required.
- When uploading files larger than 5GB.
- When the connection to the BOS server is frequently interrupted due to unstable network conditions.
- Enable streaming file uploads.
- The file size cannot be determined before uploading.
The following will introduce the implementation of Multipart Upload step by step. Suppose there is a file with the local path /path/to/file.zip. Since the file is large, it will be transmitted to BOS in parts.
Initialize multipart upload
Use initiateMultipartUpload method to initialize a multipart upload event:
1$response = $client->initiateMultipartUpload($bucketName, $objectKey);
2$uploadId =$response->uploadId;
The return result of initiateMultipartUpload contains UploadId, which is the unique identifier for distinguishing multipart upload events, and we will use it in subsequent operations.
Initialization for uploading infrequent access storage class objects
Initialize a multipart upload event for infrequent access storage:
1use BaiduBce\Services\Bos\StorageClass;
2$options = array(
3 BosOptions::STORAGE_CLASS => StorageClass::STANDARD_IA,
4);
5$bos_client->initiateMultipartUpload($bucketName, $objectName, $options);
Initialization for uploading a cold storage class object
Initialize a multipart upload event for cold storage:
1use BaiduBce\Services\Bos\StorageClass;
2$options = array(
3 BosOptions::STORAGE_CLASS => StorageClass::COLD,
4);
5$bos_client->initiateMultipartUpload($bucketName, $objectName,$options);
Upload parts
The file is then uploaded in multiple parts.
1// Set the local file to be uploaded in parts
2$fileName = "myfilename";
3$fileSize = filesize($fileName);
4 // Set the starting offset position of the part
5$offset = 0;
6$partNumber = 1;
7 // Set each part to 5MB
8$partSize = 5 * 1024 * 1024;
9$length = $partSize;
10$partList = array();
11$bytesLeft = $fileSize;
12 // Multipart upload
13while ($bytesLeft > 0) {
14 $length = ($length > $bytesLeft) ? $bytesLeft : $length;
15 $response = $client->uploadPartFromFile($bucketName, $objectKey, $uploadId, $partNumber, $fileName, $offset, $length);
16 array_push($partList, array("partNumber"=>$partNumber, "eTag"=>$response->metadata["etag"]));
17 $offset += $length;
18 $partNumber++;
19 $bytesLeft -= $length;
20}
The core of the above code is to call the UploadPart method to upload each part, but the following points should be noted:
- The UploadPart method requires each part, except the last one, to be at least 5 MB in size. However, part sizes are not validated by the Upload Part interface until completing the multipart upload process.
- To ensure no errors during network transmission, it is recommended to use the Content-MD5 value returned by BOS for each part after
UploadPartto verify the correctness of the uploaded part data. When all part data is combined into one Object, it no longer contains the MD5 value. - The part number must be within the range of 1 to 10,000. If this limit is exceeded, BOS will return an InvalidArgument error code.
- For each uploaded part, the stream must be positioned at the beginning of the respective part.
- After each Part is uploaded, the return result from BOS will include
eTagandpartNumber, which need to be saved to $partList. The type of $partList is a list, where each element is a dict. Each dict contains two keys: partNumber and eTag; these will be used in the subsequent step of completing the multipart upload.
Complete multipart upload
Complete the multipart upload as shown in the following code:
1$response = $client->completeMultipartUpload($bucketName, $objectKey, $uploadId, $partList);
2print $response->location;
The partList in the above code is the list of parts saved in the second step. After BOS receives the list of parts submitted by the user, it will verify the validity of each data Part one by one. Once all data parts are validated, BOS will assemble the data parts into a complete Object.
Cancel multipart upload
Users can cancel multipart uploads using the abortMultipartUpload method.
1$client->abortMultipartUpload($bucketName, $objectKey, $uploadId);
Retrieve unfinished multipart upload event
Users can obtain the unfinished multipart upload events in the bucket by the listMultipartUploads method.
1$response = $client->listMultipartUploads($bucketName);
2print $response->bucket;
3print $response->uploads[0]->key;
Note:
- By default, if the number of multipart upload events in a bucket surpasses 1,000, only 1,000 records will be returned. In such cases, the IsTruncated value in the response will be True, and the NextKeyMarker will indicate the starting point for the next query.
- To retrieve more multipart upload events, you can utilize the KeyMarker parameter for batch reading.
Large file upload
The BOS PHP SDK provides an encapsulated API for multipart uploads of large files: putSuperObjectFromFile. The API will upload files in parts internally, with a default part size of 5 MB. PART_SIZE can be specified.
1$filename = "/home/file.zip";
2$userMeta = array("private" => "private data");
3$options = array(
4 BosOptions::USER_METADATA => $userMeta
5);
6$client->putSuperObjectFromFile($bucket, $object, $filename, $options);
Get all uploaded information
Users can obtain all uploaded parts in an upload event by the listParts method:
1$response = $client->listParts($bucketName, $objectKey, $uploadId);
2print $response->bucket;
3print $response->uploads[0]->key;
Note:
- By default, if the number of multipart upload events in a bucket surpasses 1,000, only 1,000 records will be returned. In such cases, the IsTruncated value in the response will be True, and the NextPartNumberMarker will indicate the starting point for the next query.
- To fetch additional multipart upload events, you can utilize the PartNumberMarker parameter for batch reading.
Resumable upload
When users upload large files to BOS, if the network is unstable or the program crashes, the entire upload will fail, and the parts that have been uploaded before the failure will also be invalid. Users have to start over. This not only wastes resources but also often fails to complete the upload after multiple retries in an unstable network environment. Based on the above scenarios, BOS provides the capability of resumable upload:
- In a generally stable network, it is recommended to use the three-step upload method, dividing the object into 5 MB blocks, refer to [Multipart Upload](#Multipart upload).
- If your network condition is very poor, it is recommended to use the appendObject method for resumable upload, appending small data (256 KB) each time, refer to [Append Upload](#Append upload).
Tips
- Resumable upload is an encapsulation and enhancement of multipart upload, implemented using multipart upload;
- For large files or poor network environments, it is recommended to use multipart upload;
Download file
The BOS PHP SDK provides a variety of file download APIs, allowing users to download files from BOS in the following ways:
- Simple streaming download
- Download to a local file
- Resumable download
- Range download
Simple streaming download
Users can read the object into a stream using the following code:
1$client->getObjectAsString($bucketName, $objectKey);
Directly download an object to a file
Users can download an object to the specified file using the following code:
1$client->getObjectToFile($bucketName, $objectKey, $fileName);
Range download
To implement more functions, you can configure the RANGE parameter through options to specify the download range to achieve more refined acquisition of the object. If the specified download range is 0-100, it will return data from byte 0 to byte 100, including byte 100, with a total of 101 bytes of data, i.e., [0, 100]. The format of the RANGE parameter is array($offset, $endset), where both variables are long integers in bytes. Users can utilize this function to achieve segmented download and resumable upload of files.
1$options = array(
2 BosOptions::RANGE=>array(0,100),
3);
4$client->getObjectToFile($bucketName, $objectKey, $fileName, $options);
Other methods
Get the storage class of the object
The storage class attributes of an object are divided into STANDARD (standard storage), STANDARD_IA (infrequent access storage), and COLD (cold storage). This can be achieved through the following code:
1$response = $client->getObjectMetadata($bucketName, $objectKey);
2echo $response[BosOptions::STORAGE_CLASS];
Get only ObjectMetadata
The getObjectMetadata method retrieves only the ObjectMetadata, not the object itself. See the sample code below:
1$response = $client->getObjectMetadata($bucketName, $objectKey);
2echo $response[BosOptions::ETAG];
The parameters available for calling in the getObjectMetadata parsing class are:
| Parameters | Description |
|---|---|
| contentType | Object type |
| contentLength | Object size |
| contentMd5 | Object MD5 |
| etag | The HTTP protocol entity tag of object |
| storageClass | Storage class of the object |
| userMetadata | If userMetadata custom meta is specified in PutObject, this item will be returned |
Change file storage class
As previously mentioned, BOS supports three storage classes for files: STANDARD (standard storage), STANDARD_IA (infrequent access storage), and COLD (cold storage). The BOS PHP SDK also provides functionality for users to modify a file's storage class.
The relevant parameters are as follows:
| Parameters | Description |
|---|---|
| x-bce-storage-class | Define the object's storage class. STANDARD_IA indicates infrequent access storage, COLD indicates cold storage, and if no class is specified, the default is standard storage. |
An example is as follows:
1use BaiduBce\Services\Bos\StorageClass;
2$options = array(
3 BosOptions::STORAGE_CLASS => StorageClass::STANDARD_IA,
4);
5 // Convert standard storage to infrequent access storage
6$client->copyObject($bucket, $key, $bucket, $key, $options);
7$response = $client->getObjectMetadata($bucket, $key);
8echo $response[BosOptions::STORAGE_CLASS];
9$options = array(
10 BosOptions::STORAGE_CLASS => StorageClass::COLD,
11);
12 // Convert infrequent access storage to cold storage
13$client->copyObject($bucket, $key, $bucket, $key, $options);
14$response = $client->getObjectMetadata($bucket, $key);
15echo $response[BosOptions::STORAGE_CLASS];
Get file download URL
Users can obtain the URL of a specified object through the following code:
1use BaiduBce\Services\Bos\BosClient;
2use BaiduBce\Services\Bos\BosOptions;
3use BaiduBce\Auth\signOptions;
4$client = new BoSClient($BOS_CONFIG);
5$signOptions = array(
6 SignOptions::TIMESTAMP=>new \DateTime(),
7 SignOptions::EXPIRATION_IN_SECONDS=>300,
8);
9$url = $client->generatePreSignedUrl($bucket,
10 $key,
11 array(BosOptions::SIGN_OPTIONS => $signOptions)
12 );
Description:
- Before calling this function, users need to manually set the endpoint to the domain name of the corresponding region. Baidu AI Cloud currently supports multiple regions. Please refer to [Region Selection Guide](Reference/Region Selection Instructions/Region.md). Currently, the supported regions include "North China-Beijing," "South China-Guangzhou" and "East China-Suzhou." Beijing region:
http://bj.bcebos.com, Guangzhou region:http://gz.bcebos.com, Suzhou region:http://su.bcebos.com.EXPIRATION_IN_SECONDSis the specified URL validity period, calculated from the current time. It is an optional parameter, and the system default value is 1,800 seconds if not configured. To set a permanent non-expiration time, theExpirationInSecondsparameter can be set to -1. You cannot set it to any other negative value.TIMESTAMPis an optional parameter. If not configured, the system defaults TIMESTAMP to the current time.- If the file to be obtained is expected to be publicly readable, the corresponding URL link can be quickly concatenated and obtained through simple rules:
http://$bucket.$region.bcebos.com/$objectorhttp://$region.bcebos.com/$bucket/$object.
It now supports getting through the STS method. For configuring STS to access BOS, see the initialization page. The code example is as follows:
1$signOptions = array(
2 SignOptions::TIMESTAMP=>new \DateTime(),
3 SignOptions::EXPIRATION_IN_SECONDS=>1800,
4);
5$url = $client->generatePreSignedUrl($bucket,
6 $key,
7 array(BosOptions::SIGN_OPTIONS => $signOptions, BosOptions::PARAMS => array('x-bce-security-token' => $sessionToken))
8 );
9echo $url;
List files in the storage space
The BOS SDK allows users to list objects in the following two ways:
- Simple listing
- Advanced listing via parameters
In addition, users can also simulate folders while listing files.
Simple listing
To quickly and easily obtain a list of desired files, users can retrieve the bucket's object list using the listObjects method.
1$client->listObjects($bucketName);
Note:
- If the number of objects in a bucket exceeds 1,000, only 1,000 objects will be returned by default.
- To retrieve more objects, the marker parameter can be used to enable batch reading.
Advanced listing via parameters
In addition to the simple listing mentioned above, users can also configure optional parameters through options to implement various flexible query functions. The settable parameters are as follows:
| Parameters | Function | |
|---|---|---|
| PREFIX | Restrict the returned object keys to those starting with a specific prefix | setPrefix(String prefix) |
| DELIMITER | A character used to group object names. Only objects containing the specified prefix and appearing for the first time are included. Objects between the delimiter characters are treated as a single group element: CommonPrefixes. | |
| MARKER | Set the result to start returning from the first object in alphabetical order after the marker | |
| MAX_KEYS | Set the maximum number of objects to return, with a default and upper limit of 1,000. Specifying a value greater than 1,000 will default to 1,000. |
Note:
- If there is an object named with the prefix, when querying only with prefix, all returned keys will still include the object named with the Prefix. For details, see [Recursively List All Files in a Directory](#Simulate folder function).
- If there is an object named with the prefix, when querying with the combination of prefix and delimiter, there will be Null in all returned keys, and the key names do not contain the prefix. For details, see [View Files and Subdirectories in a Directory](#Simulate folder function).
The following are several examples to illustrate the method of listing via parameters:
Specify the maximum number of returned items
1//Specify the maximum number of returned items as 500
2$options = array(
3 BosOptions::MAX_KEYS=>500,
4);
5$response = $client->listObjects($bucket, $options);
Return objects with a specified prefix
1//Specify to return objects with the prefix "usr"
2$options = array(
3 BosOptions::PREFIX=>"usr",
4);
5$response = $client->listObjects($bucket, $options);
Return from after a specified object
1//Users can define to exclude a certain object and start returning from after it
2$options = array(
3 BosOptions::MARKER=>"object",
4);
5$response = $client->listObjects($bucket, $options);
Pagination to get all objects
Users can set a maximum of 500 records per page
1$options = array(
2 BosOptions::MAX_KEYS => 500,
3);
4$isTruncated = true;
5while($isTruncated) {
6 $res = $client->listObjects($bucket, $options);
7 $isTruncated = $res->isTruncated;
8 if (property_exists($res, 'nextMarker')) {
9 $options[BosOptions::MARKER] = $res->nextMarker;
10 }
11}
Results of paginated restoration of all objects after a specific object
Users can set a maximum of 500 records per page and start getting from after a specific object
1$options = array(
2 BosOptions::MAX_KEYS => 500,
3 BosOptions::MARKER => "object",
4);
5$isTruncated = true;
6while($isTruncated) {
7 $res = $client->listObjects($bucket, $options);
8 $isTruncated = $res->isTruncated;
9 if (property_exists($res, 'nextMarker')) {
10 $options[BosOptions::MARKER] = $res->nextMarker;
11 }
12}
The parameters available for calling in the resolution class returned by the listObjects method are as follows:
| Parameters | Description |
|---|---|
| name | Bucket name |
| prefix | The matched objects from prefix to the first Delimiter character are returned as a group of elements |
| marker | Starting point of this query |
| maxKeys | Maximum number of requests returned |
| isTruncated | Indicate whether all queries are returned; false - all results are returned this time; true - not all results are returned this time |
| contents | A container for the returned objects |
| +key | Object name |
| +lastModified | Last modification time of the object |
| +eTag | The HTTP protocol entity tag of object |
| +storageClass | Storage class of object |
| +size | The size of the object content (in bytes) |
| +owner | User information of the bucket corresponding to the object |
| ++id | User ID of bucket owner |
| ++displayName | Name of bucket owner |
Simulate folder function
BOS storage does not have a native folder concept. Everything is stored as objects. However, for easier management, BOS users often organize files using folder structures.
To facilitate this, BOS allows the creation of simulated folders by creating objects with a size of 0. These objects can be uploaded and downloaded, and are displayed as folders if they end with “/” in the console.
By combining the delimiter and prefix parameters, users can simulate folder functionalities. The combined effect of delimiter and prefix is as follows:
When a prefix is set to a folder name, files starting with that prefix—including all files and subfolders contained within—are listed recursively. File names will appear in contents.
If the delimiter is set to /, only the files and top-level subfolders within the folder are listed. Names of subfolders are returned in CommonPrefixes. Files and folders nested within these subfolders are not displayed.
The following are several application methods:
List all files in the bucket
When users need to get all files under a bucket, they can refer to [Pagination to Get All Objects](#Advanced listing via parameters)
Recursively list all files in a directory
You can obtain all files in the dir directory by setting the Prefix parameter:
1$options = array(
2 BosOptions::PREFIX => "dir/",
3);
4$isTruncated = true;
5while($isTruncated) {
6 $res = $client->listObjects($bucket, $options);
7 $isTruncated = $res->isTruncated;
8 if (property_exists($res, 'nextMarker')) {
9 $list_options[BosOptions::MARKER] = $res->nextMarker;
10 }
11}
View files and subdirectories in a directory
With the combination of Prefix and Delimiter, it can list files and subdirectories under the the dir directory:
1$options = array(
2 BosOptions::PREFIX => "dir/",
3 BosOptions::DELIMITER => "/",
4);
5$isTruncated = true;
6while($isTruncated) {
7 $res = $client->listObjects($bucket, $options);
8 $isTruncated = $res->isTruncated;
9 if (property_exists($res, 'nextMarker')) {
10 $list_options[BosOptions::MARKER] = $res->nextMarker;
11 }
12}
List storage properties of objects in a bucket
After users complete the upload, if they need to view the storage class properties of all objects in a specified bucket, it can be achieved through the following code:
1use BaiduBce\Services\Bos\StorageClass;
2$response = $bos_client->listObjects($bucketName);
3$objectList = $response->contents;
4for ($i= 0;$i< count($objectList); $i++){
5 echo $objectList[$i]->storageClass;
6}
Restore objects
After users archive a file, they can restore it. The file must be in a frozen status to be restored.
1$client->restoreObject($bucket, $archiveKey, $archiveDay);
Object permission control
Set access permission for an object.
The following code sets the object's permission to private:
1$canned_acl = array("x-bce-acl" => "private");
2$client->setObjectCannedAcl($bucket, $key, $canned_acl);
Among them, three parameters are encapsulated in CannedAcl.php: ACL_PRIVATE, ACL_PUBLIC_READ, ACL_PUBLIC_READ_WRITE, and their corresponding permissions are: private, public-read and public-read-write respectively. Currently, object permission control supports the first two types. For specific details about permissions, please refer to BOS API Documentation [Object Access Control](BOS/API Reference/Access control.md#Object permission control).
Set access permissions for a specified user on an object
BOS provides the setObjectAcl method and setObjectCannedAcl method to set access permissions for specified users on an object. You can refer to the following code:
- Set access permissions for specified users through
x-bce-grant-readandx-bce-grant-full-controlin setObjectCannedAcl.
1$canned_acl = array("x-bce-grant-read" => "id=\"7f34788d02a64a9c98f85600567d98a7\",id=\"7f34788d02a64a9c98f85600567d98a8\"");
2$client->setObjectCannedAcl($bucket, $object, $canned_acl);
3$canned_acl = array("x-bce-grant-full-control" => "id=\"7f34788d02a64a9c98f85600567d98a7\",id=\"7f34788d02a64a9c98f85600567d98a8\"");
4$client->setObjectCannedAcl($bucket, $object, $canned_acl);
- Set object access permission via setObjectAcl
1$my_acl = array(
2 array(
3 'grantee' => array(
4 array(
5 'id' => '7f34788d02a64a9c98f85600567d98a7',
6 ),
7 array(
8 'id' => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
9 ),
10 ),
11 'permission' => array('FULL_CONTROL'),
12 ),
13);
14$client->setObjectAcl($bucket, $object, $my_acl);
Note:
- The permission settings in Permission include two values:
READandFULL_CONTROL, which correspond to relevant permissions respectively.- When specifying two or more grantees, refer to the format shown in the example above. Merging arrays will result in an error.
View object permissions
The following code can be used to check the object permissions:
1$response = $client->getObjectAcl($bucket, $object);
The parameters available for calling in the resolution class returned by the getObjectAcl method are as follows:
| Parameters | Description |
|---|---|
| accessControlList | Identify the permission list of the object |
| grantee | Identify the grantee |
| -id | Authorized person ID |
| permission | Identify the grantee permissions |
Delete object permissions
The following code can be used to delete the object permissions:
1$response = $client->deleteObjectAcl($bucket, $object);
Delete file
Delete single file
The following code can be referenced to delete an object:
1$client->deleteObject($bucket, $object);
Delete multiple files
The following code can be referenced to delete mutiple objects:
1$deleteattay = array(
2 array(
3 "key"=>$diping_key
4 ),
5 );
6$client->deleteMultipleObjects($bucket, $deleteattay);
Check if a file exists
Users can check if a file exists through the following operations:
1try {
2 $client->getObjectMetadata($bucket, $object);
3} catch (\BaiduBce\Exception\BceBaseException $e) {
4 if ($e->getStatusCode() == 404) {
5 echo $object . " not exist!";
6 }
7}
Get and update file meta information
File metadata, or object metadata, describes the attributes of files uploaded to BOS. It includes two types: HTTP standard attributes (HTTP headers) and user-defined metadata.
Get file meta information
Refer to [Get only ObjectMetadata](#Other methods).
Modify file meta information
BOS modifies object metadata by copying the object. When copying, set the destination bucket and object as the source bucket and object, then apply the new metadata. If new metadata is not specified, an error will occur.
1$userMeta = array("private" => "newvalue");
2$contentType ="text/plain"
3$options = array(
4 BosOptions::USER_METADATA => $userMeta,
5 BosOptions::CONTENT_TYPE=>$contentType
6);
7$client->copyObject($bucket, $key, $bucket, $key,$options);
8$response = $client->getObjectMetadata($bucket, $key);
9echo $response['userMetadata']['private']
Copy Object
Copy a file
Users can copy an object using the copyObject method, as shown in the following code:
1$client->copyObject($sourceBucketName, $sourceObjectKey, $targetBucketName, $targetObjectKey);
The copyObject method can be used to configure optional parameters through options; the parameter list is as follows:
| Parameters | Description |
|---|---|
| USER_METADATA | User-defined Meta, including Key-Value pairs |
| ETAG | When selecting the ETag of the source object for upload, the ETags of the source and target objects are compared. An error will occur if they do not match. |
1use BaiduBce\Services\Bos\BosOptions;
2$userMeta = array("private" => "private data");
3$options = array(
4 BosOptions::USER_METADATA => $userMeta
5);
6$client->copyObject($sourceBucketName, $sourceObjectKey, $targetBucketName, $targetObjectKey, $options);
Synchronous copy
Currently, BOS’s CopyObject API operates in a synchronous manner. This means BOS waits until the copy operation is fully completed before returning a success status. While synchronous copying provides a more accurate status for users, it also takes longer and is proportional to the file size.
The synchronous copy approach aligns better with industry standards and improves compatibility with other platforms. It also simplifies the server’s business logic and enhances service efficiency.
Using an SDK version earlier than bce-php-sdk-0.8.17 may lead to situations where a copy request succeeds but the file itself fails to copy. It is recommended to use the latest version of the SDK.
Multipart copy
Apart from using the CopyObject API for copying, BOS offers another method—Multipart Upload Copy. This method is suitable for the following application scenarios (but not limited to these):
- When a resumable copy process is required.
- For copying files larger than 5GB.
- When the connection to the BOS server frequently disconnects due to poor network conditions.
The following section introduces the step-by-step process for implementing the three-step copy method.
The three-step copy includes three steps: init, “copy part”, and complete. Among them, the operations of init and complete are the same as those in multipart upload. You can directly refer to [Initialize Multipart Upload](#Multipart upload) and [Complete Multipart Upload](#Multipart upload).
1$partNumber = 1;
2$offSet = 0;
3 // Set each part to 5MB
4$partSize = 5 * 1024 * 1024;
5$length = $partSize;
6$partList = array();
7$bytesLeft = $client->getObjectMetadata($sourceBucketName, $sourceKey)["contentLength"];
8 // Multipart upload
9while ($bytesLeft > 0) {
10 $length = ($length > $bytesLeft) ? $bytesLeft : $length;
11 $options = array(
12 BosOptions::RANGE => array($offSet, $offSet + $length - 1)
13 );
14 $response = $client->uploadPartCopy($sourceBucketName, $sourceKey, $targetBucketName, $targetKey, $uploadId, $partNumber, $options);
15 array_push($partList, array("partNumber"=>$partNumber, "eTag"=>$response->eTag));
16 $partNumber++;
17 $bytesLeft -= $length;
18 $offSet += $length;
19}
Note: The size parameter is in bytes and defines the size of each part. Except for the last part, the size of other parts must be larger than 5MB.
Fetch object
The following code retrieves resources from a specified URL and stores them in a designated bucket. This process requires the requester to have write permissions for the bucket. Only one object can be fetched at a time, and the user can specify a custom object name. For details, refer to the FetchObject API.
1use BaiduBce\Services\Bos\BosOptions;
2$options = array(
3 BosOptions::STORAGE_CLASS => "STANDARD",
4 BosOptions::BCE_FETCH_MODE => "async"
5);
6$fetchSource = "dowload_url";
7$client->fetchObject(
8 $bucketName,
9 $objectName,
10 $fetchSource,
11 $options
12 );
User credit quota
Set user credit quota
The following code is used to set the user credit quota
1$client->putUserQuota($maxBucketCount, $maxCapacityMegaBytes, $maxObjectCount);
Obtain user credit quota
The following code is used to get the user credit quota
1$client->getUserQuota();
Delete user credit quota
The following code is used to delete the user credit quota
1$client->deleteUserQuota();
Compliance retention
Initialize compliance retention
1$client->initBucketObjectLock($BUCKET_NAME, $retentDays);
Obtain compliance retention
1$client->getBucketObjectLock($BUCKET_NAME);
Delete compliance retention
1$client->deleteBucketObjectLock($BUCKET_NAME);
Extend compliance retention
The following code can extend the retention period
1$client->extendBucketObjectLock($BUCKET_NAME);
Event notification
Create event notification
The following code is used to create an event notification
1$mynotification =
2 array(
3 array(
4 'id'=> "water-test-1",
5 'name'=> "water-rule-1",
6 'appId'=> "water-app-id-1",
7 'status'=> "enabled",
8 'resources'=> array("/*.jpg", "/*.png"),
9 'events'=> array("PutObject") ,
10 'apps'=> array(
11 array(
12 'id' => "app-id-1",
13 'eventUrl' => "https://op-log-app-service.chehejia.com/op-log-app-service/v1-0/log/bos/event",
14 'xVars' => "xvars",
15 ),
16 ),
17 ));
18$client->putNotification($bucket, $mynotification);
Obtain event
The following code is used to get an event notification
1$getRes = $client->getNotification($bucket);
Delete event notification
The following code is used to delete an event
1$client->deleteNotification($bucket);
