File uploads let users send files to your app. Streaming helps handle big files smoothly without waiting for the whole file at once.
0
0
File uploads and streaming in Remix
Introduction
When users need to upload profile pictures or documents.
When your app processes large files like videos or backups.
When you want to show upload progress without freezing the page.
When you want to save server memory by processing files bit by bit.
When you want to store files directly to cloud storage while uploading.
Syntax
Remix
import { json } from '@remix-run/node'; import type { ActionFunction } from '@remix-run/node'; export const action: ActionFunction = async ({ request }) => { const formData = await request.formData(); const file = formData.get('file'); if (!(file instanceof File)) { return json({ error: 'No file uploaded' }, { status: 400 }); } // Example: read file stream const stream = file.stream(); // Process stream or save file here return json({ message: 'File uploaded successfully' }); };
Use request.formData() to get uploaded files from the form.
Files come as File objects with a stream() method for streaming content.
Examples
Get the file from form data and start streaming its content.
Remix
const formData = await request.formData(); const file = formData.get('file'); if (file instanceof File) { const stream = file.stream(); // handle stream }
Check if the uploaded data is actually a file before processing.
Remix
if (!(file instanceof File)) { return json({ error: 'No file uploaded' }, { status: 400 }); }
Send a JSON response confirming the upload.
Remix
return json({ message: 'File uploaded successfully' });
Sample Program
This Remix action handles a file upload from a form. It reads the file as a stream and counts the total bytes received. Then it returns a JSON message with the file size.
Remix
import { json } from '@remix-run/node'; import type { ActionFunction } from '@remix-run/node'; export const action: ActionFunction = async ({ request }) => { const formData = await request.formData(); const file = formData.get('file'); if (!(file instanceof File)) { return json({ error: 'No file uploaded' }, { status: 400 }); } // Read the file stream (example: count bytes) const reader = file.stream().getReader(); let totalBytes = 0; while (true) { const { done, value } = await reader.read(); if (done) break; totalBytes += value.byteLength; } return json({ message: `Uploaded file size: ${totalBytes} bytes` }); };
OutputSuccess
Important Notes
Always check if the uploaded data is a File before processing.
Streaming files helps avoid loading large files fully into memory.
Use browser DevTools Network tab to see file upload progress and request details.
Summary
File uploads let users send files to your Remix app.
Use request.formData() and check for File objects.
Streaming files helps handle large uploads efficiently.