首页 > PHP > Laravel直接使用H5上传到oss

Laravel直接使用H5上传到oss

2025-03-03 15:12:17

在 Laravel 项目中实现 H5 Form 直接上传文件到阿里云 OSS,可按以下步骤操作:

1. 安装依赖包

使用 Composer 安装 jacobcyl/ali-oss-storage 扩展包,用于 Laravel 与阿里云 OSS 的集成:

 

 

composer require jacobcyl/ali-oss-storage

2. 配置阿里云 OSS 信息

在 .env 文件中添加阿里云 OSS 的必要配置:

ALIYUN_OSS_ACCESS_ID=your-access-key-id
ALIYUN_OSS_ACCESS_KEY=your-access-key-secret
ALIYUN_OSS_ENDPOINT=your-endpoint
ALIYUN_OSS_BUCKET=your-bucket-name

3. 配置文件系统

在 config/filesystems.php 中添加阿里云 OSS 的磁盘配置:

'disks' => [
    // 其他磁盘配置...
    'aliyun-oss' => [
        'driver'     => 'aliyun-oss',
        'access_id'  => env('ALIYUN_OSS_ACCESS_ID'),
        'access_key' => env('ALIYUN_OSS_ACCESS_KEY'),
        'bucket'     => env('ALIYUN_OSS_BUCKET'),
        'endpoint'   => env('ALIYUN_OSS_ENDPOINT'),
        'isCName'    => false,
        'secureUrl'  => false,
    ],
],

4. 创建获取签名的控制器方法

创建一个控制器方法,用于生成阿里云 OSS 的上传签名,以便 H5 Form 可以直接上传文件到 OSS。以下是一个示例控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use OSS\OssClient;
use OSS\Core\OssException;

class OssSignatureController extends Controller
{
    public function getSignature()
    {
        $accessId = config('filesystems.disks.aliyun-oss.access_id');
        $accessKey = config('filesystems.disks.aliyun-oss.access_key');
        $endpoint = config('filesystems.disks.aliyun-oss.endpoint');
        $bucket = config('filesystems.disks.aliyun-oss.bucket');

        $ossClient = new OssClient($accessId, $accessKey, $endpoint);

        $expire = 30; // 签名有效期,单位为秒
        $now = time();
        $end = $now + $expire;
        $expiration = gmdate('Y-m-d\TH:i:s\Z', $end);

        $dir = 'uploads/'; // 上传目录

        $condition = [0 => 'content-length-range', 1 => 0, 2 => 1048576000];
        $conditions[] = $condition;

        $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
        $conditions[] = $start;

        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        $policy = json_encode($arr);
        $base64Policy = base64_encode($policy);
        $stringToSign = $base64Policy;
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKey, true));

        $response = array(
            'accessid' => $accessId,
            'host' => 'https://' . $bucket . '.' . $endpoint,
            'policy' => $base64Policy,
            'signature' => $signature,
            'expire' => $end,
            'dir' => $dir,
        );

        return response()->json($response);
    }
}

5. 定义获取签名的路由

在 routes/api.php 或 routes/web.php 中定义路由,用于调用上述控制器方法:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\OssSignatureController;

Route::get('/oss/signature', [OssSignatureController::class, 'getSignature']);

6. 创建 H5 Form 页面

创建一个 HTML 页面,使用 JavaScript 获取签名并生成表单,实现直接上传到阿里云 OSS:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload to OSS</title>
</head>

<body>
    <form id="uploadForm" action="" method="post" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </form>

    <script>
        fetch('/oss/signature')
          .then(response => response.json())
          .then(data => {
                const form = document.getElementById('uploadForm');
                form.action = data.host;

                const inputAccessId = document.createElement('input');
                inputAccessId.type = 'hidden';
                inputAccessId.name = 'OSSAccessKeyId';
                inputAccessId.value = data.accessid;
                form.appendChild(inputAccessId);

                const inputPolicy = document.createElement('input');
                inputPolicy.type = 'hidden';
                inputPolicy.name = 'policy';
                inputPolicy.value = data.policy;
                form.appendChild(inputPolicy);

                const inputSignature = document.createElement('input');
                inputSignature.type = 'hidden';
                inputSignature.name = 'Signature';
                inputSignature.value = data.signature;
                form.appendChild(inputSignature);

                const inputKey = document.createElement('input');
                inputKey.type = 'hidden';
                inputKey.name = 'key';
                inputKey.value = data.dir + '${filename}';
                form.appendChild(inputKey);
            });
    </script>
</body>

</html>

7. 注意事项

  • 跨域问题:如果出现跨域问题,需要在阿里云 OSS 控制台配置跨域规则,允许你的域名进行跨域访问。
  • 安全问题:签名的有效期和上传目录等信息需要根据实际需求进行合理设置,以保障系统安全。

通过以上步骤,你就可以在 Laravel 项目中实现 H5 Form 直接上传文件到阿里云 OSS。

使用 Ctrl+D 可将网站添加到书签
收藏网站
扫描二维码
关注早实习微信公众号
官方公众号
Top