Generate Video Thumbnails in the Browser Before Upload with React
A video file the user selects can be turned into thumbnail images in the browser before it is sent to the server. Load the file into a <video> element that is not shown on the page, seek to a frame with currentTime, wait for the seek to finish, draw the frame to a <canvas>, and convert it to a JPEG with toBlob(). Even without server-side video processing, you can send the image of the chosen frame along with the video.
Here we build a component that creates three candidates at 10%, 50%, and 90% of the video's length, and sends the one the user picks along with the video in a FormData. We also cover what happens when you draw before the seek finishes, which shows the previous frame, and how unreadable video formats are handled, along with the test results.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, and Playwright 1.63.0. The videos were 10-second test files made with ffmpeg (H.264 MP4 and MOV, VP9 WebM, HEVC MP4, and an MP4 with rotation metadata), and I selected them with Playwright. I did not test Firefox, Safari, mobile browsers, videos actually recorded on a smartphone, or large videos (several hundred MB or more). I checked the orientation of the video with rotation metadata only in Chromium, using the MP4 test file.

A function that cuts out a frame and turns it into a JPEG
The cutting logic is grouped into a function that does not depend on React. createThumbnails() takes a video file and an array of ratios relative to the length, and returns the frame at each position as a JPEG no wider than 320px.
export type Thumbnail = { time: number; blob: Blob; width: number; height: number };
// Wait until the event of the given type fires on video. Reject on "error" if the video cannot be loaded
function waitFor(video: HTMLVideoElement, type: 'loadedmetadata' | 'seeked') {
return new Promise<void>((resolve, reject) => {
const done = () => { cleanup(); resolve(); };
const fail = () => { cleanup(); reject(new Error(`動画を読み込めません(${video.error?.message || 'error'})`)); };
const cleanup = () => {
video.removeEventListener(type, done);
video.removeEventListener('error', fail);
};
video.addEventListener(type, done);
video.addEventListener('error', fail);
});
}
function toBlob(canvas: HTMLCanvasElement) {
return new Promise<Blob>((resolve, reject) => {
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('画像にできませんでした'))), 'image/jpeg', 0.8);
});
}
// Make JPEGs no wider than maxWidth from the frames at the given ratios (0 to 1) of the video's length
export async function createThumbnails(file: File, ratios: number[], maxWidth = 320): Promise<Thumbnail[]> {
const src = URL.createObjectURL(file);
const video = document.createElement('video');
video.muted = true;
video.preload = 'auto';
try {
const loaded = waitFor(video, 'loadedmetadata');
video.src = src;
await loaded;
if (!video.videoWidth) throw new Error('映像が入っていないか、このブラウザでは映像を表示できません');
const scale = Math.min(1, maxWidth / video.videoWidth);
const canvas = document.createElement('canvas');
canvas.width = Math.round(video.videoWidth * scale);
canvas.height = Math.round(video.videoHeight * scale);
const ctx = canvas.getContext('2d')!;
const thumbs: Thumbnail[] = [];
// Seek one video element in turn, so wait for each one (do not change currentTime at the same time)
for (const ratio of ratios) {
const time = video.duration * ratio;
const seeked = waitFor(video, 'seeked');
video.currentTime = time;
await seeked; // Draw only after the seek has finished
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
thumbs.push({ time, blob: await toBlob(canvas), width: canvas.width, height: canvas.height });
}
return thumbs;
} finally {
video.removeAttribute('src');
video.load();
URL.revokeObjectURL(src);
}
}
The flow is as follows.
URL.createObjectURL()creates a URL that points to the selected file, and puts it in thesrcof a<video>element that is not shown on the page.- Wait for
loadedmetadata. At this point the length (duration) and the video size (videoWidthandvideoHeight) are known. - For each ratio, set
currentTime, wait forseeked, and then draw to the canvas withdrawImage(). - Pass
'image/jpeg'and quality0.8totoBlob()to get a JPEG Blob.
Finally, in finally, the src is removed and the URL is released with URL.revokeObjectURL(). MDN explains that you should release a URL with this method once you are done with it. If you do not, the browser keeps a reference to the file.
When toBlob() cannot create an image, it passes null to the callback. The code treats that case as a failure.
Drawing before the seek finishes shows the previous frame
Setting a value on currentTime does not change the frame immediately. You can tell when the seek has finished from the seeked event. I used a test video (black for 0 to 1 seconds, light blue for 1 to 4 seconds, pink for 4 to 7 seconds, and yellow for 7 to 10 seconds) to check what appears on the canvas depending on when it is drawn.
| When drawn | What appeared |
|---|---|
Right after loadedmetadata (readyState is 1) |
Nothing (transparent) |
After loadeddata (the current frame has loaded), right after setting currentTime = 5 at 0 seconds |
Black (the 0-second frame) |
After waiting for seeked |
Pink (the 5-second frame) |
Then set currentTime = 9 and wait with setTimeout(0) |
Pink (the previous 5-second frame) |
After waiting for seeked |
Yellow (the 9-second frame) |
Even after waiting a short time with setTimeout(0), the seek had not finished (seeking was true), so the previous frame appeared. Waiting for seeked is more reliable than waiting for a fixed amount of time. The MDN notes on drawImage() also say that a video must have a readyState greater than 1 to be drawn.
seeked also fired when I set currentTime to the current time (I checked this by setting 9 at the 9-second position). In the Chromium test environment, the same ratio listed twice did not cause the wait to hang.
Because one <video> element seeks through the frames, createThumbnails() moves to the next position only after it has waited for seeked and finished drawing the current one.
If you choose the 0-second frame, this test video produces a black image. For videos that start black or fade in, the 0-second frame will not show much. This is why this article builds the candidates from the 10% position.
A component that picks a candidate and sends it with the video
VideoThumbnailPicker shows a file input, three candidates, and a submit button. Clicking a candidate changes selected, and when the form is submitted, the Blob of that one candidate is added to the FormData.
import { useEffect, useRef, useState } from 'react';
import type { ChangeEvent, FormEvent } from 'react';
import { createThumbnails } from './videoThumbnail';
import type { Thumbnail } from './videoThumbnail';
const RATIOS = [0.1, 0.5, 0.9]; // Positions at 10%, 50%, and 90% of the video
export function VideoThumbnailPicker() {
const [file, setFile] = useState<File | null>(null);
const [thumbs, setThumbs] = useState<(Thumbnail & { url: string })[]>([]);
const [selected, setSelected] = useState(0);
const [status, setStatus] = useState('');
const latestFile = useRef<File | null>(null);
// Create the URLs when a file is selected, and release them in the cleanup function
useEffect(() => () => thumbs.forEach((t) => URL.revokeObjectURL(t.url)), [thumbs]);
async function handleChange(e: ChangeEvent<HTMLInputElement>) {
const f = e.target.files?.[0] ?? null;
latestFile.current = f;
setFile(f);
setThumbs([]);
setSelected(0);
if (!f) return setStatus('');
setStatus('サムネイルを作っています…');
try {
const result = await createThumbnails(f, RATIOS);
if (latestFile.current !== f) return; // Another file was selected in the meantime
setThumbs(result.map((t) => ({ ...t, url: URL.createObjectURL(t.blob) })));
setStatus('');
} catch (err) {
if (latestFile.current !== f) return;
setStatus(err instanceof Error ? err.message : String(err));
}
}
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const thumb = thumbs[selected];
if (!file || !thumb) return;
const body = new FormData();
body.append('video', file);
body.append('thumbnail', thumb.blob, 'thumbnail.jpg');
setStatus('送信しています…');
const res = await fetch('/upload', { method: 'POST', body });
setStatus(res.ok ? `送信しました:${await res.text()}` : `送信に失敗しました(${res.status})`);
}
return (
<form onSubmit={handleSubmit}>
<label>
動画を選ぶ <input type="file" accept="video/*" onChange={handleChange} />
</label>
{thumbs.length > 0 && (
<div className="thumbs" role="group" aria-label="サムネイルの候補">
{thumbs.map((t, i) => (
<button
key={t.time}
type="button"
aria-pressed={i === selected}
onClick={() => setSelected(i)}
>
<img src={t.url} width={t.width} height={t.height} alt={`${t.time.toFixed(1)}秒の場面`} />
<span>{t.time.toFixed(1)}秒</span>
</button>
))}
</div>
)}
<p role="status">{status}</p>
<button type="submit" disabled={!thumbs.length}>この画像で送信</button>
</form>
);
}
The URLs for display are created with URL.createObjectURL(t.blob) in the handler (handleChange) after the candidates are ready, and they are released by the cleanup function of useEffect. As described in the official useEffect reference, the cleanup function is called with the old values when the dependency array changes, and also when the component is removed from the screen. When you select another video, the URLs of the previous three candidates are released.
In testing, I counted the calls to URL.revokeObjectURL(). After selecting the first video, there was one call (for the video URL inside createThumbnails()). After selecting the second video, the total was five. The four added calls were one for the second video's URL and three for the previous candidate URLs. The count was the same in the development build with StrictMode, and all three images were displayed.
latestFile is there in case another video is selected while thumbnails are still being created. If processing for the earlier video finishes later, its result is discarded because it no longer matches latestFile. The screen therefore keeps the candidates for the most recently selected video.
When sending, the third argument to FormData.append() sets the file name. A Blob has no original file name, so without this argument the name would be "blob". I sent the 5.0-second candidate to a test server that returns what it receives. The server got both the video and the JPEG, as shown below.
送信しました:video=sample.mp4(video/mp4、218587バイト) / thumbnail=thumbnail.jpg(image/jpeg、4310バイト)
From a 1280×720 video, it produced a 320×180 JPEG of about 4 KB. This size is for a test video with a single solid color and text only.
Results with videos in different formats and orientations
I used the same component with videos in different formats.
| Video | Result |
|---|---|
| H.264 MP4 | Three images were created at 1.0 s, 5.0 s, and 9.0 s (320×180) |
| VP9 WebM | Three images were also created |
| H.264 MOV | Three images were also created |
| HEVC (H.265) MP4 | Chromium in the test environment could not load it, and an error event fired |
| MP4 with "rotate 90 degrees for display" metadata | Three tall images were created (320×569) |
In the Chromium test environment, an HEVC video fired error, and createThumbnails() failed. The screen then showed a message containing video.error.message, as follows.
動画を読み込めません(PipelineStatus::DEMUXER_ERROR_NO_SUPPORTED_STREAMS: FFmpegDemuxer: no supported streams)
Even with the same .mp4 extension, a file may fail to load depending on the format of the video inside. It is safer not to skip the handling that waits for error and reports the failure. video.error.message gives a detailed description for looking into the cause of the error. In the actual UI, it is friendlier to replace it with a message such as "This video format is not supported."
For the video with rotation metadata, the original video is 1280×720 landscape. In Chromium, videoWidth and videoHeight were 720×1280, and the thumbnails were also drawn in portrait. I also checked side by side that the orientation matched the display in a <video> element. createThumbnails() sets the canvas size from videoWidth and videoHeight, so no code was needed to swap the width and height.





