Content is user-generated and unverified.
// actions.js "use server"; // In-memory storage for chunk tracking (in production, use Redis or database) const uploadSessions = new Map(); export async function fileUploadAction(prevState, formData) { try { const chunkData = JSON.parse(formData.get('chunkData')); const chunkIndex = parseInt(formData.get('chunkIndex')); const totalChunks = parseInt(formData.get('totalChunks')); const fileName = formData.get('fileName'); const fileSize = parseInt(formData.get('fileSize')); const uploadId = formData.get('uploadId'); const benpos = formData.get('benpos'); const isLastChunk = formData.get('isLastChunk') === 'true'; // Initialize upload session if it doesn't exist if (!uploadSessions.has(uploadId)) { uploadSessions.set(uploadId, { chunks: new Map(), fileName, fileSize, benpos, totalChunks, receivedChunks: 0 }); } const session = uploadSessions.get(uploadId); // Store the chunk session.chunks.set(chunkIndex, chunkData); session.receivedChunks++; console.log(`Received chunk ${chunkIndex + 1}/${totalChunks} for ${fileName}`); // Send chunk to backend const response = await fetch('http://localhost:3000/x', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ chunkData: chunkData, chunkIndex: chunkIndex, totalChunks: totalChunks, fileName: fileName, fileSize: fileSize, uploadId: uploadId, benpos: benpos, isLastChunk: isLastChunk }) }); if (!response.ok) { throw new Error(`Backend responded with status: ${response.status}`); } const result = await response.json(); // If this is the last chunk or we've received all chunks, clean up if (session.receivedChunks === totalChunks) { uploadSessions.delete(uploadId); return { type: "success", messages: { upload: `File ${fileName} uploaded successfully! Total chunks: ${totalChunks}` } }; } // Return success for individual chunk return { type: "success", messages: { chunk: `Chunk ${chunkIndex + 1}/${totalChunks} processed successfully` } }; } catch (error) { console.error('Error in fileUploadAction:', error); return { type: "error", messages: { error: `Upload failed: ${error.message}` } }; } }
Content is user-generated and unverified.
    Updated Next.js Actions for Chunked Upload | Claude