Current Location: Home> Latest Articles> How to Integrate Qiniu Cloud Storage in ThinkPHP6 for File Uploads

How to Integrate Qiniu Cloud Storage in ThinkPHP6 for File Uploads

gitbox 2025-06-27

Integrating the Qiniu Cloud Storage SDK

To use Qiniu Cloud Storage in ThinkPHP6, you first need to include Qiniu's official PHP SDK. Add the following dependency to your composer.json file:


"require": {
    "qiniu/php-sdk": "^7.3"
}

Then run the following command to update your dependencies:


composer update

Setting Up Qiniu Cloud Configuration

Create a configuration file named qiniu.php inside the config directory of your ThinkPHP6 project. This file will store your Qiniu credentials and related settings:


return [
    'accessKey' => 'your-access-key',
    'secretKey' => 'your-secret-key',
    'bucket'    => 'your-bucket',
    // Other settings...
];

Writing the Controller to Handle File Uploads

In your controller, use Qiniu's UploadManager and Auth classes to upload files. Here's a sample implementation:


use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

class QiniuController extends Controller
{
    public function upload()
    {
        $file = $_FILES['file']['tmp_name'];

        $accessKey = config('qiniu.accessKey');
        $secretKey = config('qiniu.secretKey');
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken(config('qiniu.bucket'));

        $uploadMgr = new UploadManager();
        $key = null; // Automatically generate a unique filename
        list($ret, $err) = $uploadMgr->putFile($token, $key, $file);

        if ($err !== null) {
            echo 'Upload failed';
        } else {
            echo 'Upload successful';
        }
    }
}

Creating the Upload Form in the View

To allow users to upload files from the frontend, add a basic form to your view file:


<form action="/qiniu/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Upload File</button>
</form>

This form submits a POST request to the controller and handles the file upload process.

Conclusion

This guide covered the complete process of integrating Qiniu Cloud Storage into ThinkPHP6, from including the SDK to writing backend upload logic and frontend forms. By leveraging Qiniu, developers can store and manage files in the cloud efficiently, providing a better and more reliable experience for users.