Qiniu Cloud Object Storage enables simple file uploads.
The official documentation also includes sample code; simply replace the placeholder for your API key and storage bucket name to test file uploading.
<?php
require 'vendor/autoload.php';
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;
// 用于签名的公钥和私钥
$accessKey = '';
$secretKey = '';
$bucket = '';
// 初始化签权对象
$auth = new Auth($accessKey, $secretKey);
$token = $auth->uploadToken($bucket);
// 要上传文件的本地路径
$filePath = './370009-2.png';
// 上传到存储后保存的文件名
$key = 'test/370009-2.png';
// 初始化 UploadManager 对象并进行文件的上传。
$uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传。
list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath, null, 'application/octet-stream', true, null, 'v2');
echo "\n====> putFile result: \n";
if ($err !== null) {
var_dump($err);
} else {
var_dump($ret);
}Code Interpretation
This code snippet implements file uploading using the PHP SDK for Qiniu Cloud Object Storage Service. The following is an analysis of the code:
- Import dependency libraries
First, the dependency library 'vendor/autoload.php' required for the Qiniu PHP SDK is introduced; since no specific path is provided, it is evident that the SDK was installed using Composer within the project's current directory.
- Key value and Bucket name
Assign the values of accessKey, secretKey, and bucket to respective variables. accessKey、`secretKey` and `$bucket`: these values are derived from the Access Key and Secret Key created in the Qiniu Cloud backend account, as well as the name of the storage space (Bucket) to be uploaded to.
- Initialize signing object
Use `accessKey` and `secretKey` to initialize an `Auth` object; this object is used for signing operations to prevent unauthorized access to API requests and ensure data security.
- Get upload credentials
Call the `uploadToken` method on the signing object to obtain the upload token `$token`; this token contains all the necessary parameters required for uploading a file, such as upload policy, upload storage space, upload expiration time, and more.
- Upload file
Use the UploadManager object to call the `putFile` method to upload a local file to the specified Bucket.The `token` parameter serves as the upload credential.`key` is the filename of the file to be uploaded and stored in the Bucket; `$filePath` is the local file path of the file to be uploaded. When using this method to upload a file, you can also specify optional upload parameters, such as the file type or whether to overwrite an existing file with the same name.
- Output upload result
Finally, use the `var_dump()` function to output the upload results ($ret and $err); if $err is `null`, it indicates a successful upload; otherwise, it indicates a failed upload – in this case, you can examine the error message contained in $err.