以下是一个简单的PHP分片上传代码示例:
<?php
$targetDir = "uploads/"; // 上传目录
$chunkDir = "chunks/"; // 分片目录
if (!empty($_FILES) && isset($_POST['chunkIndex']) && isset($_POST['totalChunks']) && isset($_POST['fileName'])) {
$chunkIndex = $_POST['chunkIndex'];
$totalChunks = $_POST['totalChunks'];
$fileName = $_POST['fileName'];
// 创建分片目录
if (!file_exists($chunkDir)) {
mkdir($chunkDir, 0777, true);
}
// 保存分片文件
$tempFilePath = $chunkDir . $fileName . '_' . $chunkIndex;
move_uploaded_file($_FILES['file']['tmp_name'], $tempFilePath);
// 检查是否已上传所有分片
for ($i = 0; $i < $totalChunks; $i++) {
if (!file_exists($chunkDir . $fileName . '_' . $i)) {
die('{"status":"incomplete"}');
}
}
// 合并所有分片
$targetFilePath = $targetDir . $fileName;
$targetFile = fopen($targetFilePath, 'wb');
for ($i = 0; $i < $totalChunks; $i++) {
$chunkFilePath = $chunkDir . $fileName . '_' . $i;
$chunkFile = fopen($chunkFilePath, 'rb');
stream_copy_to_stream($chunkFile, $targetFile);
fclose($chunkFile);
unlink($chunkFilePath);
}
fclose($targetFile);
echo '{"status":"success"}';
} else {
echo '{"status":"error"}';
}
?>
以下是一个简单的PHP分片下载代码示例:
<?php
$filePath = "path/to/file"; // 文件路径
$chunkSize = 1024 * 1024; // 分片大小(1MB)
if (file_exists($filePath)) {
$fileSize = filesize($filePath);
$handle = fopen($filePath, 'rb');
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . basename($filePath) . "\"");
header("Content-Length: " . $fileSize);
$bytesSent = 0;
while (!feof($handle) && !connection_aborted()) {
$chunk = fread($handle, $chunkSize);
echo $chunk;
$bytesSent += strlen($chunk);
flush();
}
fclose($handle);
} else {
echo "File not found.";
}
?>
注意:以上代码仅为示例,可能需要根据实际需求进行修改和优化。
上一篇:弹窗口 php
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站