To validate file upload in JavaScript by what a photo shows, check three things after the upload: whether there is a page in the photo, whether it has text, and whether it is the right document. Two Filestack features do the checking, Document Detection finds the page and OCR reads the words on it, so the form enables its submit button only for the right photo. We built it with a plain <input type="file">, the JavaScript file upload library from a script tag, and a small Node server with no packages.
An expense form that asks for a photo of the receipt also gets holiday photos, blank pages and delivery notes, and finance finds them a week later. Every one of those files is an image of a sensible size, so the usual type and size check passes them all:
const file = input.files[0];
if (!file.type.startsWith('image/')) return 'Upload an image';
if (file.size > 20 * 1024 * 1024) return 'That file is over 20 MB';
A photo of a wall of sake barrels passes both lines.
Key takeaways
- Type and size checks pass any photo. Checking content means asking whether there is a page, whether it has text and whether the text belongs to the document the field asks for.
doc_detectionwithcoords:truereturns a box even when there is no page in the photo. A zero or negative width or height means no page was found.- Count the OCR words inside the box to tell a page from scenery, then look for a word the document carries, such as “total” on a receipt.
- Keep the result on the server and refuse the form unless the photo passed. A disabled button in the browser is a hint, not a check.
- A photo with no page costs one Document Detection call. A photo that reaches OCR costs one of each.
What type and size checks cannot see
A browser can tell you a file’s name, its MIME type and its size, and the HTML upload basics cover the attributes that check them. It cannot tell you what is in the picture. There are four ways to validate file upload in JavaScript by what the photo shows:
| Option | What it catches | The catch |
|---|---|---|
accept="image/*" and a size limit |
PDFs, videos, huge files | Any photo of anything |
| Someone in finance looks at each photo | Everything | Days after the person who uploaded it has moved on |
| An image classifier in the browser | Photos that do not look like documents | You ship, host and retrain a model |
| Read the photo on your server after upload | No page, unreadable page, wrong document | One or two calls per photo, a few seconds of wait |
We recommend the last option, and it is the one we built. It runs while the person is still on the form, so the message reaches someone who can take a better photo.
Validate file upload in JavaScript in three questions
The server asks three questions, in this order, and stops at the first “no”.
Is there a page in the photo? doc_detection finds a page in a photo. By default it returns the page as a cropped, straightened image. With coords:true it returns where the page is instead:
{"coords":{"height":1384,"width":1113,"x":408,"y":346}}
It answers 200 whether or not there is a page. For a photo of a street lamp in a mountain town, the same call returns {"coords":{"height":-1651,"width":0,"x":234,"y":1882}}. A width or height of zero or less means no page. The document detection parameters cover the image outputs.
Is there text on it? A box with a sensible size is not proof on its own. For a snow-covered building the call returns a plausible 1341 by 1121 box, and for a taxi at night it returns the whole frame. ocr reads every word in the photo with its position, so the check counts only the words whose centre falls inside the box. The receipts and forms below have dozens. The scenery photos have a few stray letters from signs, or none.
Is it the right document? A wall of sake barrels has 46 words inside its box, so it gets past the count. What it does not have is the word “total”, which a receipt prints. So the check also asks for a word the document carries.
Here is what the check returns for the photos used in this post:
| Photo | Page found | Words in the page | Result |
|---|---|---|---|
| Receipt on a table | Yes | 36 | Accepted |
| Faded receipt | Yes | 36 | Accepted |
| Invoice photographed with a phone | Yes | 115 | Accepted, an invoice has a total too |
| Delivery note | Yes | 41 | Rejected, wrong document |
| Wall of sake barrels | Yes | 46 | Rejected, wrong document |
| Blank sheet of paper | Yes | 0 | Rejected, no text |
| Taxi at night | Whole frame | 7 | Rejected, no text |
| Station sign | No | Rejected, no page | |
| Street lamp in a mountain town | No | Rejected, no page | |
| A PDF picked instead of a photo | Rejected, not a photo |
Sign the requests on a small server
Document Detection and OCR run on Start, Grow and Scale, and both need a signed policy on every request. The policy needs the read and convert calls. Without a signature, the call returns 403 security required for tasks: doc_detection, and a policy without convert returns call is not allowed: (call: convert). Policies can also grant store, remove and the other calls listed in the security policy reference.
The server is plain Node with no packages. It needs Node 20.6 or later for --env-file, and a .env file holding your API key and app secret, both from the Developer Portal:
FILESTACK_API_KEY=YOUR_API_KEY
FILESTACK_APP_SECRET=YOUR_APP_SECRET
filestack.mjs signs policies. It hands the browser a five-minute policy that can only upload, and signs each read of an uploaded photo with a policy tied to that photo’s handle:
import { createHmac } from 'node:crypto';
const CDN = 'https://cdn.filestackcontent.com';
export function sign(policyFields) {
const expiry = Math.floor(Date.now() / 1000) + 300;
const policy = Buffer.from(JSON.stringify({ ...policyFields, expiry }))
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_');
const signature = createHmac('sha256', process.env.FILESTACK_APP_SECRET)
.update(policy)
.digest('hex');
return { policy, signature };
}
// What the browser needs to upload one file: the key and a five-minute store policy
export function uploadPolicy() {
const key = process.env.FILESTACK_API_KEY;
return { apikey: key, ...sign({ call: ['pick', 'store'] }) };
}
export async function getJson(tasks, handle) {
const { policy, signature } = sign({ call: ['read', 'convert'], handle });
const res = await fetch(`${CDN}/security=p:${policy},s:${signature}/${tasks}/${handle}`);
if (!res.ok) throw Object.assign(new Error(await res.text()), { status: res.status });
return res.json();
}
The app secret never leaves the server. The API key does go to the browser, because the upload library needs it, and the policy limits what the browser can do with it. Signed policies are one of the controls behind a secure file upload, along with the domain whitelist covered below.
Check the photo
check.mjs asks the three questions. Phone photos can be larger than the 20,000,000 pixels doc_detection accepts, and a larger photo returns 400 ... Image too large. Maximum allowed size: 20,000,000 px. So both calls read a copy resized to 2000 pixels wide. Reading the same copy also means the word positions from ocr and the box from doc_detection use the same pixels.
import { getJson } from './filestack.mjs';
// Both calls read the same 2000 px wide copy, so their pixel positions line up
const SIZE = 'resize=width:2000';
const MIN_WORDS = 15;
const MESSAGES = {
not_a_photo: 'Upload a photo of the page, as a JPEG, PNG or HEIC.',
no_page: "We couldn't find a page in this photo. Lay it flat and fill the frame.",
no_text: "We couldn't read any text in this photo. Retake it in good light, page filling the frame.",
wrong_document: (label) => `This doesn't look like a ${label}. Upload a photo of the ${label}.`,
};
const reject = (reason, label) => {
const message = MESSAGES[reason];
return { ok: false, reason, message: typeof message === 'function' ? message(label) : message };
};
// Every OCR word whose centre falls inside the detected page
function wordsInside(ocr, { x, y, width, height }) {
const words = [];
for (const area of ocr.document.text_areas)
for (const line of area.lines)
for (const word of line.words) {
const cx = word.bounding_box.reduce((sum, p) => sum + p.x, 0) / 4;
const cy = word.bounding_box.reduce((sum, p) => sum + p.y, 0) / 4;
if (cx >= x && cx <= x + width && cy >= y && cy <= y + height) words.push(word.text);
}
return words;
}
export async function checkPhoto(handle, { label, mustInclude }) {
let coords;
try {
({ coords } = await getJson(`${SIZE}/doc_detection=coords:true`, handle));
} catch (err) {
if (err.status === 400) return reject('not_a_photo');
throw err;
}
if (!(coords.width > 0 && coords.height > 0)) return reject('no_page');
const words = wordsInside(await getJson(`${SIZE}/ocr`, handle), coords);
if (words.length < MIN_WORDS) return reject('no_text');
const text = words.join(' ').toLowerCase();
if (!mustInclude.some((word) => text.includes(word))) return reject('wrong_document', label);
return { ok: true, words: words.length };
}
MIN_WORDS is 15 because, on the photos above, the documents have 34 or more words inside the page and the scenery has 7 or fewer. Run your own sample of good and bad uploads through try-check.mjs below and set the number between the two groups.
mustInclude is the part that knows what the field is for. Use ['total'] for receipts, ['invoice'] for invoices, or a few words for a form, such as ['claim', 'policy']. The match is on lowercase text inside the page, so a receipt that prints TOTAL matches.
A PDF fails at the resize step with a 400, and the check reports it as “not a photo”. If the field should also take PDFs, send those to your PDF handling before this check.
Block submit until the photo passes
The browser uploads the photo, asks the server to check it and enables the submit button only when the check passes. The server keeps every result and refuses the form if its photo did not pass, because a disabled button stops nobody who sends the form another way. If a call to Filestack fails, for example on an expired signature, /check returns 502 and the form asks the person to try again:
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { uploadPolicy } from './filestack.mjs';
import { checkPhoto } from './check.mjs';
// What this form's photo field has to be
const FIELD = { label: 'receipt', mustInclude: ['total'] };
// Results by handle. Use your database in production.
const checked = new Map();
function send(res, status, body, type = 'application/json') {
res.writeHead(status, { 'Content-Type': type });
res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body));
}
async function readBody(req) {
let body = '';
for await (const chunk of req) body += chunk;
return body;
}
createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
const route = `${req.method} ${url.pathname}`;
if (route === 'GET /') return send(res, 200, await readFile('index.html'), 'text/html');
if (route === 'GET /upload-policy') return send(res, 200, uploadPolicy());
if (route === 'POST /check') {
const handle = url.searchParams.get('handle') ?? '';
if (!/^[A-Za-z0-9]{20}$/.test(handle)) return send(res, 400, { ok: false, message: 'Bad handle' });
try {
const result = await checkPhoto(handle, FIELD);
checked.set(handle, result);
return send(res, result.ok ? 200 : 422, result);
} catch (err) {
console.error(handle, err.status, err.message);
return send(res, 502, { ok: false, message: 'We could not check the photo. Try again.' });
}
}
if (route === 'POST /submit') {
const form = new URLSearchParams(await readBody(req));
if (!checked.get(form.get('receipt'))?.ok) {
return send(res, 422, 'Upload a photo of the receipt first.', 'text/plain');
}
return send(res, 200, `Claim saved with receipt ${form.get('receipt')}`, 'text/plain');
}
send(res, 404, 'Not found', 'text/plain');
}).listen(8790, () => console.log('http://localhost:8790'));
The form is a normal HTML form with one hidden field for the photo’s handle. The HTML form upload example shows the same library in a form without the check:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Expense claim</title>
<form method="post" action="/submit">
<label>Amount <input name="amount" required></label>
<label>Receipt photo <input id="photo" type="file" accept="image/*" required></label>
<input type="hidden" name="receipt" id="receipt">
<p id="status" role="status"></p>
<button id="submit" disabled>Submit claim</button>
</form>
<script src="https://static.filestackapi.com/filestack-js/4.x.x/filestack.min.js"></script>
<script>
const photo = document.getElementById('photo');
const status = document.getElementById('status');
const submit = document.getElementById('submit');
const receipt = document.getElementById('receipt');
photo.addEventListener('change', async () => {
submit.disabled = true;
receipt.value = '';
const file = photo.files[0];
if (!file) return;
if (file.size > 20 * 1024 * 1024) {
status.textContent = 'That photo is over 20 MB. Take a new one.';
return;
}
status.textContent = 'Checking the photo...';
try {
const { apikey, policy, signature } = await (await fetch('/upload-policy')).json();
const client = filestack.init(apikey, { security: { policy, signature } });
const { handle } = await client.upload(file);
const result = await (await fetch(`/check?handle=${handle}`, { method: 'POST' })).json();
status.textContent = result.ok ? 'Receipt photo accepted.' : result.message;
if (result.ok) {
receipt.value = handle;
submit.disabled = false;
}
} catch {
status.textContent = 'The upload failed. Try again.';
}
});
</script>
client.upload sends the file straight from the browser to storage and resolves with its handle. The upload error handling post covers retries and the network failures behind them.
If your application has a domain whitelist, add the address your form runs on, localhost included. A page served from an address that is not on the list gets 403 {"error":"forbidden"} when the upload starts. The domain whitelist settings are in the Developer Portal.
Run it locally
Put the four files and .env in one folder, then start the server:
node --env-file=.env server.mjs
Open http://localhost:8790, pick a photo of a receipt and then a photo of anything else. The status line under the field shows the result, and the submit button enables only for the receipt.
To tune MIN_WORDS and mustInclude, skip the form and run the check on handles you have already uploaded. try-check.mjs takes them as arguments:
import { checkPhoto } from './check.mjs';
// node --env-file=.env try-check.mjs HANDLE [HANDLE...]
for (const handle of process.argv.slice(2)) {
const started = Date.now();
const result = await checkPhoto(handle, { label: 'receipt', mustInclude: ['total'] });
console.log(handle, `${((Date.now() - started) / 1000).toFixed(1)}s`, JSON.stringify(result));
}
node --env-file=.env try-check.mjs HANDLE_1 HANDLE_2 HANDLE_3
For a receipt, the sake barrels and the street lamp, it prints:
60XaFWuSRNmxqTGwhlpX 2.5s {"ok":true,"words":36}
K8utZD7xQhqIf6cMyv6G 3.0s {"ok":false,"reason":"wrong_document","message":"This doesn't look like a receipt. Upload a photo of the receipt."}
8FAakgEGTxCdqM8qMNzO 1.4s {"ok":false,"reason":"no_page","message":"We couldn't find a page in this photo. Lay it flat and fill the frame."}
On these photos a check takes between one and five seconds after the upload finishes, and a photo with no page returns fastest because it never reaches OCR.
Where the content check sits next to the other checks
Run the cheap checks first. accept="image/*" and the size limit cost nothing and stop a video before it uploads. The content check runs after the upload, because it reads the stored photo. The submit check runs last, on the server.
Each photo that reaches OCR uses one Document Detection call and one OCR unit. A photo with no page uses only the Document Detection call.
A rejected photo is already stored when the check runs. To delete it, send a DELETE to https://www.filestackapi.com/api/file/HANDLE with your key and a policy that has the remove call. /check accepts any handle in your application, so delete only handles your form uploaded, or have a nightly job remove the ones that never reached /submit.
If you would rather use the picker than a plain file input, the file uploader hands you the same handle in its upload callback, and the rest of this post does not change. Once a photo is accepted, the same OCR response holds the merchant, the date and the total, which is where intelligent document processing takes over from validation.
Carl is a Product Marketing Manager at Filestack with four years of hands-on experience in React, JavaScript, Django, and Python. He bridges the gap between product and developer, translating how Filestack’s APIs and SDKs actually work into content that’s useful for the engineers building with them. His writing covers file handling workflows, upload integrations, and real-world implementation patterns, written from the perspective of someone who has built with these tools firsthand.
Read More →

