PHP code example of tinywan / storage
1. Go to this page and download the library: Download tinywan/storage library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
tinywan / storage example snippets
$res = Tinywan\Storage\Storage::uploadFile();
var_dump(json_encode($res));
'local' => [
'adapter' => \Tinywan\Storage\Adapter\LocalAdapter::class,
'root' => public_path() . '/storage',
],
// 示例:上传到阿里云 OSS
$res = \Tinywan\Storage\Storage::disk(\Tinywan\Storage\Storage::MODE_OSS)->uploadFile();
public function upload(Request $request)
{
$base64 = $request->post('base64');
$response = \Tinywan\Storage\Storage::disk(\Tinywan\Storage\Storage::MODE_OSS, false)->uploadBase64($base64, 'png');
var_dump($response);
}
$serverFile = runtime_path() . DIRECTORY_SEPARATOR . 'storage/webman.png';
$res = \Tinywan\Storage\Storage::disk(\Tinywan\Storage\Storage::MODE_OSS, false)->uploadServerFile($serverFile);
'storage' => [
'chunk_size' => 1024 * 1024 * 5, // 单个分片的大小限制,默认5M
'local' => [
// ...
'chunk_path' => runtime_path() . '/storage/.chunks', // 分片临时存储目录,默认 {root}/.chunks
],
],
public function uploadChunk(Request $request)
{
$file = $request->file('file'); // 单个分片文件
$fileId = $request->post('file_id'); // 文件唯一标识,由前端生成(字母数字开头,仅允许字母、数字、下划线、中划线,长度不超过64)
$chunkIndex = (int) $request->post('chunk_index'); // 分片序号,从0开始
$chunkMd5 = $request->post('chunk_md5'); // 当前分片的md5,服务端会校验
return \Tinywan\Storage\Storage::disk(\Tinywan\Storage\Storage::MODE_LOCAL, false)
->uploadChunk($file, $fileId, $chunkIndex, $chunkMd5);
}
$progress = \Tinywan\Storage\Storage::disk(\Tinywan\Storage\Storage::MODE_LOCAL, false)
->chunkProgress($fileId, $totalChunks);
$result = \Tinywan\Storage\Storage::disk(\Tinywan\Storage\Storage::MODE_LOCAL, false)
->mergeChunk($fileId, $totalChunks, 'video.mp4'); // 文件名仅用于提取扩展名并做
$storage = \Tinywan\Storage\Storage::disk('oss', false); // oss / cos / qiniu / s3
$storage->uploadChunk($file, $fileId, $chunkIndex, $chunkMd5);
$storage->chunkProgress($fileId, $totalChunks);
$result = $storage->mergeChunk($fileId, $totalChunks, 'video.mp4');
$result = $storage->mergeChunk($fileId, $totalChunks, 'video.mp4', [
'file_hash' => $wholeFileSha1, // 可选:整文件散列,作为最终对象名
'mime_type' => 'video/mp4', // 可选:云端无法探测 MIME,默认 application/octet-stream
]);
text
runtime/storage/fd2d472da56c71a6da0a5251f5e1b586.png
mermaid
flowchart LR
A[📄 大文件] --> B[✂️ 前端按 chunk_size 切片]
B --> C[📤 逐片 uploadChunk<br/>服务端 md5 校验]
C --> D{断网/失败?}
D -- 是 --> E[🔍 chunkProgress<br/>查询缺失分片补传]
E --> C
D -- 否 --> F[🔗 mergeChunk<br/>流式合并 + 散列命名]
F --> G[✅ 正式文件落盘<br/>清理临时分片]