Upload a file to compare response sizes.
JSON definition · shared/definitions/store-files.json
View on GitHub
{
"title": "Expense report",
"completeText": "Submit expense report",
"elements": [
{
"type": "text",
"name": "purpose",
"title": "Purpose of the expense",
"isRequired": true
},
{
"type": "file",
"name": "receipt",
"title": "Receipts",
"storeDataAsText": false,
"allowMultiple": true,
"maxSize": 5242880,
"acceptedTypes": "image/png,image/jpeg,image/webp,image/gif,application/pdf",
"isRequired": true,
"waitForUpload": true,
"description": "PNG, JPEG, WebP, GIF, or PDF files up to 5 MB each"
}
]
}
Client · shared/client/store-files.js · sjs:store-files.client
View on GitHub
// Upload: your server stores the files and returns an id (or a URL) for each
survey.onUploadFiles.add(async (_, options) => {
const body = new FormData();
options.files.forEach(file => body.append("files[]", file)); // "files[]": PHP keeps only the last of several "files"
const response = await fetch("/api/files", { method: "POST", body }).catch(() => null);
const ids = response?.ok ? await response.json().catch(() => null) : null;
if (!Array.isArray(ids) || ids.length !== options.files.length || ids.some(id => typeof id !== "string" || !id)) {
return options.callback([], ["Couldn't upload files. Please try again."]);
}
// The response stores these ids, not the file contents
options.callback(options.files.map((file, i) => ({ file, content: ids[i] })));
});
Client · shared/client/store-files.js · sjs:store-files.preview
View on GitHub
// Preview: only when the stored value is not a public URL the browser can open
survey.onDownloadFile.add(async (_, options) => {
try {
const res = await fetch(`/api/files/${encodeURIComponent(options.content)}`);
if (!res.ok) throw new Error("Preview unavailable");
const reader = new FileReader();
reader.onload = () => options.callback("success", reader.result);
reader.onerror = () => options.callback("error");
reader.readAsDataURL(await res.blob());
} catch {
options.callback("error");
show("file-status", "Couldn't load the preview. The file may be missing or inaccessible.");
}
});
Server · routes/store-files.js · sjs:store-files.server
View on GitHub
// POST /api/files — store uploads, return their ids in the same order
// Field "files[]", the name on every platform: PHP keeps only the last of several fields named "files"
app.post("/api/files", upload.array("files[]"), (req, res) => {
const files = req.files ?? [];
if (files.length === 0) throw httpError(422, 'Upload one or more files in a field named "files[]"');
const types = files.map((file) => detectType(file.buffer)); // by the bytes, never the client's Content-Type
const refused = files.find((file, i) => !TYPES.includes(types[i]));
if (refused) throw httpError(422, `${refused.originalname} is not a PNG, JPEG, WebP, GIF or PDF file`);
const ids = files.map((file, i) => {
const id = randomUUID(); // stored by id, never by the client's file name
writeFileSync(join(filesDir(req), id), file.buffer);
db(req).prepare("INSERT INTO files (id, name, type) VALUES (?, ?, ?)").run(id, file.originalname, types[i]);
return id;
});
res.json(ids);
}, uploadErrors);
Server · routes/store-files.js · sjs:store-files.download
View on GitHub
// GET /api/files/:id — the content, for private files only; check access first
app.get("/api/files/:id", (req, res) => {
const file = db(req).prepare("SELECT id, name, type FROM files WHERE id = ?").get(req.params.id);
if (!file || !canReadFile(req.user, file)) throw httpError(404, "Not found"); // 404, not 403: don't confirm the file exists
// nosniff and sandbox: an uploaded HTML or SVG never runs as this site
res.set({ "Content-Type": file.type, "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "sandbox" });
res.sendFile(file.id, { root: filesDir(req), dotfiles: "deny" });
});