Files
upload_big_files/upload.php

45 lines
1.9 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$fileChunk = $_FILES['file_chunk'];
$chunkIndex = (int)$_POST['chunk_index'];
$totalChunks = (int)$_POST['total_chunks'];
$originalFilename = basename($_POST['filename']);
// Временный файл для хранения склеиваемых частей
$tempFilePath = $uploadDir . $originalFilename . '.part';
// Открываем временный файл для дозаписи (режим append)
$out = fopen($tempFilePath, 'ab');
if ($out) {
// Открываем переданную часть файла для чтения
$in = fopen($fileChunk['tmp_name'], 'rb');
if ($in) {
// Переносим данные из части в общий файл
stream_copy_to_stream($in, $out);
fclose($in);
}
fclose($out);
} else {
header('Content-Type: application/json; charset=utf-8');
exit(json_encode(['status' => 'error', 'message' => 'Не удалось открыть временный файл', 'size'=>0]));
}
// Если это последняя часть, переименовываем файл в итоговый
if ($chunkIndex === $totalChunks - 1) {
$finalFilePath = $uploadDir . $originalFilename;
rename($tempFilePath, $finalFilePath);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 'success', 'message' => 'Файл успешно собран', 'path' => $finalFilePath, 'size'=>filesize($finalFilePath)]);
} else {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 'uploading', 'chunk' => $chunkIndex, 'size' => filesize($tempFilePath)]);
}
}
?>