JSON definition · shared/definitions/creator-uploads.json
View on GitHub
{
"title": "Customer support",
"description": "Tell us how we can help",
"elements": [
{
"type": "image",
"name": "help_image",
"imageLink": "/shared/samples/support-help.svg",
"altText": "Support resources",
"imageHeight": "180",
"imageWidth": "100%"
},
{
"type": "dropdown",
"name": "product",
"title": "Product",
"choices": [
"Form Library",
"Survey Creator",
"Dashboard",
"PDF Generator"
]
},
{
"type": "comment",
"name": "issue",
"title": "How can we help?",
"isRequired": true
}
]
}
Client · shared/client/creator-uploads.js · sjs:creator-uploads.client
View on GitHub
// Store each uploaded image separately and keep its URL in the form schema
creator.onUploadFile.add(async (_, options) => {
const label = options.propertyName === "logo" || options.elementType === "header" ? "Logo" : "Image";
uploads++; updateControls();
showError("");
try {
if (!options.files.length || options.files.some(file =>
file.size > 5242880 || !["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)))
throw new Error("Choose a PNG, JPEG, WebP, or GIF image up to 5 MB.");
const body = new FormData();
options.files.forEach(file => body.append("files[]", file));
const response = await fetch("/api/files", { method: "POST", body });
const ids = response.ok ? await response.json() : null;
if (!Array.isArray(ids) || ids.length !== options.files.length ||
ids.some(id => typeof id !== "string" || !id))
throw new Error(`Couldn't upload the ${label.toLowerCase()}. Please try again.`);
options.callback("success", `/api/files/${encodeURIComponent(ids[0])}`);
note(`${label} uploaded.`, "ok");
} catch (error) {
options.callback("error");
showError(error.message);
note(error.message, "error");
} finally { uploads--; updateControls(); }
});
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/CreatorLoadSave.cs · sjs:creator-load-save.server
View on GitHub
// PUT /api/forms/{id} — store the definition as-is: it's one JSON document
app.MapPut("/api/forms/{id}", async (string id, HttpRequest request, ClaimsPrincipal user, IAuthorizationService auth, SurveyDb db) =>
{
var allowed = await auth.AuthorizeAsync(user, "edit-forms"); // editing is an admin action: 403 otherwise
if (!allowed.Succeeded)
return Results.Json(new { error = allowed.Failure?.FailureReasons.FirstOrDefault()?.Message }, statusCode: 403);
// The raw body, not a bound class: binding would drop the keys the class doesn't know and re-format numbers
var definition = await StoredJson.ReadBodyAsync(request);
await StoredJson.UpsertAsync(db, StoredTable.Forms, id, definition); // stored as it arrived: 1.0 stays 1.0
return Results.NoContent(); // the next page load renders the new version
});