Home > PHP Framework > ThinkPHP > body text

How to use ThinkPHP6 to implement OSS file upload and download operations?

PHPz
Release: 2023-06-12 11:28:40
Original
2571 people have browsed it

With the continuous development of Internet technology, cloud storage services have attracted more and more attention. Alibaba Cloud Object Storage (OSS) is a secure, stable, and highly scalable cloud storage service used to store massive amounts of data. This article will introduce how to use the ThinkPHP6 framework to implement Alibaba Cloud OSS file upload and download operations.

1. Create Alibaba Cloud OSS Bucket

First, you need to create a Bucket for storing files on the Alibaba Cloud official website. Bucket is equivalent to a folder in the cloud, used to store files uploaded to Alibaba Cloud OSS. The method of creating a Bucket is beyond the scope of this article. Readers can consult relevant tutorials on the Alibaba Cloud official website.

After creation, you need to obtain the following three parameters:

1. AccessKeyId: the user ID for accessing OSS.
2. AccessKeySecret: User key for accessing OSS.
3. Endpoint: the address of the OSS service.

These parameters will be used in subsequent code implementation.

2. Install Alibaba Cloud OSS SDK

Before using Alibaba Cloud OSS SDK, you need to install it. You can use composer to install, the command is as follows:

composer require aliyuncs/oss-sdk-php

After the installation is complete, you need to create the oss.php configuration file in the config directory. The configuration file needs to contain the following three parameters:

'accessKeyId' => 'Alibaba Cloud AccessKeyId',
'accessSecret' => 'Alibaba Cloud AccessKeySecret',
'endpoint' = > 'OSS service address',

In order to facilitate the acquisition of configuration parameters, you can also define these parameters in the .env file and create an oss.php configuration file in the config directory, as shown below:

'accessKeyId' => env('OSS_ACCESS_KEY_ID'),
'accessSecret' => env('OSS_ACCESS_KEY_SECRET'),
'endpoint' => env('OSS_ENDPOINT'),

3. File upload operation

After completing the installation of Alibaba Cloud OSS SDK and configuring parameters, you can start the file upload operation. Create the upload method in the controller, the code is as follows:

use OSSOssClient;
use OSSCoreOssException;

public function upload()

{
    $accessKeyId = config('oss.accessKeyId');
    $accessKeySecret = config('oss.accessSecret');
    $endpoint = config('oss.endpoint');
    $bucket = 'your_bucket_name';

    // 创建OSSClient实例
    try {
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
    } catch (OssException $e) {
        printf(__FUNCTION__ . "阿里云OSS连接失败:error[%s]
Copy after login
Copy after login

", $e-> getMessage());

        return;
    }

    // 获取文件
    $file = request()->file('file');
    if (!$file) {
        return "上传文件不能为空";
    }

    // 上传文件
    $fileName = $file->getOriginalName();
    $filePath = $file->getRealPath();
    try {
        $result = $ossClient->uploadFile($bucket, $fileName, $filePath);
    } catch (OssException $e) {
        return "文件上传失败";
    }

    if (isset($result['oss-request-url'])) {
        return "文件上传成功";
    } else {
        return "文件上传失败";
    }

}
Copy after login

In the method, first obtain the three parameters when creating the Bucket before, and then create an OSSClient instance. Then obtain the uploaded file through request()->file('file'), Use the getOriginalName() method to get the original name of the uploaded file, and use the getRealPath() method to get the temporary file path of the uploaded file. Finally, use the uploadFile() method to upload the file to Alibaba Cloud OSS.

4. File Download Operation

Similar to the file upload operation, the file download operation also requires the use of the Alibaba Cloud OSS SDK. Create a download method in the controller with the following code:

use OSSOssClient;
use OSSCoreOssException;

public function download()

{
    $accessKeyId = config('oss.accessKeyId');
    $accessKeySecret = config('oss.accessSecret');
    $endpoint = config('oss.endpoint');
    $bucket = 'your_bucket_name';

    // 创建OSSClient实例
    try {
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
    } catch (OssException $e) {
        printf(__FUNCTION__ . "阿里云OSS连接失败:error[%s]
Copy after login
Copy after login

", $e->getMessage());

        return;
    }

    // 获取要下载的文件名称
    $object = 'your_object_name';

    // 下载文件
    $content = '';
    try {
        $content = $ossClient->getObject($bucket, $object);
    } catch (OssException $e) {
        return "指定的文件不存在";
    }

    if ($content !== '') {
        // 文件下载操作
    } else {
        return "文件下载失败";
    }

}
Copy after login

In the method, you also need to obtain the three parameters when creating the Bucket before. , and then create an OSSClient instance. Get the file to be downloaded through $object, and use the getObject() method to download the file locally. The file download operation can set the file type, size and other information through the header() method, and finally output the file content through echo to realize the file download operation.

The above is the entire content of how to use ThinkPHP6 to implement Alibaba Cloud OSS file upload and download operations. Through the introduction of this article, readers can master the use of Alibaba Cloud OSS SDK and gain a deeper understanding of cloud storage services.

The above is the detailed content of How to use ThinkPHP6 to implement OSS file upload and download operations?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!