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 · app/routes/store_files.py · sjs:store-files.server
View on GitHub
# POST /api/files — store uploads, return their ids in the same order
@router.post("/api/files")
async def store_files(request: Request, db: Db, files_dir: FilesDir) -> list[str]:
async with request.form(max_files=20, max_fields=20) as form: # closes the spooled uploads afterwards
# Field "files[]", the name on every platform: PHP keeps only the last of several fields named "files"
files = [f for f in form.getlist("files[]") if isinstance(f, UploadFile)]
if not files:
raise HTTPException(422, 'Upload one or more files in a field named "files[]"')
uploads = [(f, await f.read(MAX_BYTES + 1)) for f in files] # check the whole batch before storing any
for file, content in uploads:
if len(content) > MAX_BYTES:
raise HTTPException(422, "Each file must be 5 MB or less")
if detect_type(content) not in TYPES: # by the bytes, never the client's type
raise HTTPException(422, f"{file.filename} is not a PNG, JPEG, WebP, GIF or PDF file")
ids = []
for file, content in uploads:
id = str(uuid.uuid4()) # named by id, never by the client
(files_dir / id).write_bytes(content)
db.execute("INSERT INTO files (id, name, type) VALUES (?, ?, ?)", (id, file.filename, detect_type(content)))
ids.append(id)
return ids
Server · app/routes/creator_load_save.py · sjs:creator-load-save.server
View on GitHub
# PUT /api/forms/{id} — store the definition as-is: it's one JSON document
@router.put("/api/forms/{id}", status_code=204)
def save_form(id: str, definition: JsonBody, user: CurrentUser, db: Db) -> None:
if not can(user, "edit-forms"): # editing is an admin action: 403 otherwise
raise HTTPException(403, "You don't have editor rights: only editors can change forms")
# The raw body, not a Pydantic model: a model would drop the keys it doesn't declare
put(db, "forms", id, definition) # stored as it arrived: {} stays {}, 1.0 stays 1.0
# 204: the next page load renders the new version