Laravel 生成 OSS 存储路径

Laravel 生成 OSS 存储路径

上传到 OSS 都文件会根据最前面的路径来进行分区存储,请求速率超过2000次/秒时(下载、上传、删除、拷贝、获取元数据信息等操作算1次操作,批量删除N个文件、列举N个文件等操作算N次操作)会被限制请求速率、延长请求处理时间。

我们需要在路径最前面加点随机值来提高存储的分区,在路径最前面加上 2 个随机值理论上会有 (26 + 26 + 10) ^ 2 = 3844 个分区。3844 好像有点多呀,感觉加 1 个随机值也可以,哈哈哈。

获取文件扩展名可以看一下我之前写的 《Laravel 上传扩展名》

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

use Illuminate\Support\Str;

if(!function_exists('generate_filepath')) {
/**
* 生成文件路径
*
* @param string $directory 目录
* @param string $extension 扩展名
* @return string
*/
function generate_filepath(string $directory, string $extension) {
// 扩展名不能为空
if(!$extension) {
throw new \InvalidArgumentException('The extension is empty.');
}

// 生成一个随机字符串
$str = Str::random(16);

if($directory) {
// 对 Windows 目录分隔符进行转换
$directory = str_replace('\\', '/', $directory);
// 去除目录前后的目录分隔符,然后在最后面加上目录分隔符
$directory = trim($directory, '/') . '/';
}

// 完整路径拼接
return substr($str, 0, 2) . '/' . $directory . substr($str, 2) . '.' . $extension;
}
}

?>

测试

1
2
3
4
5
6
echo generate_filepath('hongfs\\', 'png');
// m6/hongfs/OlUVedDq0gQVlx.png
echo generate_filepath('hongfs/', 'png');
// tl/hongfs/9ezTWDx4c9bPFQ.png
echo generate_filepath('hong/fs', 'png');
// U0/hong/fs/SlMq2bR5Pd8gBC.png

文档

OSS性能与扩展性最佳实践

往上