Created
March 12, 2026 18:55
-
-
Save carloscarucce/9f83d632ed31a1ba6dcc931230e50d9e to your computer and use it in GitHub Desktop.
Large file upload - Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const CHUNK_SIZE = 10 * 1024 * 1024; // 10MB | |
| async function uploadFile(file) { | |
| const totalChunks = Math.ceil(file.size / CHUNK_SIZE); | |
| const init = await fetch("/api/upload/init", { | |
| method: "POST", | |
| body: JSON.stringify({ | |
| filename: file.name, | |
| size: file.size, | |
| chunks: totalChunks | |
| }), | |
| headers: { "Content-Type": "application/json" } | |
| }); | |
| const { uploadId } = await init.json(); | |
| for (let i = 0; i < totalChunks; i++) { | |
| const start = i * CHUNK_SIZE; | |
| const chunk = file.slice(start, start + CHUNK_SIZE); | |
| const formData = new FormData(); | |
| formData.append("chunk", chunk); | |
| formData.append("index", i); | |
| formData.append("uploadId", uploadId); | |
| await fetch("/api/upload/chunk", { | |
| method: "POST", | |
| body: formData | |
| }); | |
| } | |
| await fetch("/api/upload/complete", { | |
| method: "POST", | |
| body: JSON.stringify({ uploadId }), | |
| headers: { "Content-Type": "application/json" } | |
| }); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| public function init(Request $request) | |
| { | |
| $uploadId = Str::uuid()->toString(); | |
| Storage::makeDirectory("chunks/$uploadId"); | |
| return response()->json([ | |
| 'uploadId' => $uploadId | |
| ]); | |
| } | |
| public function chunk(Request $request) | |
| { | |
| $uploadId = $request->uploadId; | |
| $index = $request->index; | |
| $path = "chunks/$uploadId/$index"; | |
| Storage::put($path, file_get_contents($request->file('chunk'))); | |
| return response()->json(['status' => 'ok']); | |
| } | |
| public function complete(Request $request) | |
| { | |
| $uploadId = $request->uploadId; | |
| $chunkPath = storage_path("app/chunks/$uploadId"); | |
| $finalFile = storage_path("app/uploads/$uploadId.bin"); | |
| $chunks = scandir($chunkPath); | |
| $output = fopen($finalFile, 'ab'); | |
| foreach ($chunks as $chunk) { | |
| if ($chunk == '.' || $chunk == '..') continue; | |
| $chunkFile = fopen("$chunkPath/$chunk", 'rb'); | |
| stream_copy_to_stream($chunkFile, $output); | |
| fclose($chunkFile); | |
| } | |
| fclose($output); | |
| return response()->json(['status' => 'completed']); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment