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 · Endpoints/StoreFiles.cs · sjs:store-files.server
View on GitHub
// POST /api/files — store uploads, return their ids in the same order
app.MapPost("/api/files", async (IFormFileCollection form, SurveyDb db, RequestStorage storage, CancellationToken aborted) =>
{
var files = form.GetFiles("files[]"); // field "files[]": one file or many
if (files.Count == 0) return Results.Json(new { error = "Upload one or more files in a field named \"files[]\"" }, statusCode: 422);
var uploads = new List<(string Id, string Name, byte[] Bytes, string Type)>();
foreach (var file in files) // check the whole batch before storing any of it
{
if (file.Length > 5 * 1024 * 1024) return Results.Json(new { error = "Each file must be 5 MB or less" }, statusCode: 422);
var bytes = await FileType.ReadAllBytesAsync(file, aborted);
if (FileType.Detect(bytes) is not { } type) // the detected type, never the client's
return Results.Json(new { error = $"{file.FileName} is not a PNG, JPEG, WebP, GIF or PDF file" }, statusCode: 422);
uploads.Add((Guid.NewGuid().ToString(), file.FileName, bytes, type));
}
foreach (var upload in uploads) // named by id on disk, never by the client
{
await File.WriteAllBytesAsync(Path.Combine(storage.UploadsPath, upload.Id), upload.Bytes, aborted);
db.Files.Add(new StoredFile { Id = upload.Id, Name = upload.Name, Type = upload.Type });
}
await db.SaveChangesAsync(aborted);
return Results.Json(uploads.Select(upload => upload.Id)); // the ids, in upload order
}).DisableAntiforgery(); // called with fetch() from the same origin; with cookie auth, validate a token or use an Authorization header
Server · Endpoints/StoreFiles.cs · sjs:store-files.download
View on GitHub
// GET /api/files/{id} — the content, for private files only; check access first
app.MapGet("/api/files/{id}", async (string id, ClaimsPrincipal user, IAuthorizationService auth, SurveyDb db, RequestStorage storage, HttpResponse response) =>
{
var file = await db.Files.FindAsync(id);
if (file is null || !(await auth.AuthorizeAsync(user, file, "read-file")).Succeeded)
return Results.Json(new { error = "Not Found" }, statusCode: 404); // 404, not 403: don't confirm the file exists
response.Headers.XContentTypeOptions = "nosniff"; // nosniff and sandbox: an uploaded HTML or SVG
response.Headers.ContentSecurityPolicy = "sandbox"; // never runs as this site
return Results.File(Path.Combine(storage.UploadsPath, id), file.Type);
});