Upload a File with JSON Metadata in ASP.NET Core
ASP.NET Core · Published · CoreUpload team
A file often belongs to a record and needs a caption, category or description. Keep the bytes and metadata contracts explicit, especially when the interface uploads several files before the final form is submitted.
Use one multipart body with a JSON text part
FormData can contain a binary file and ordinary text fields. Serialize structured metadata into one text part with a documented schema. Do not Base64-encode a large file merely to place it inside a JSON document: that changes transfer size and memory behavior without solving ownership or validation.
const form = new FormData();
form.append("file", selectedFile);
form.append("metadata", JSON.stringify({ caption, categoryId }));
const response = await fetch("/attachments", {
method: "POST",
body: form,
headers: { "X-XSRF-TOKEN": requestToken }
});
if (!response.ok) throw new Error("The attachment was not accepted.");This client fragment assumes selectedFile and requestToken already exist, and that the server uses that antiforgery header name. It does not define an attachments endpoint. Let the browser set the multipart boundary. A record ID belongs in the contract only when the server can verify the caller may modify that record.
Validate the metadata separately from the file
On the server, check that exactly the expected file part exists, then parse metadata into a narrow DTO. Reject malformed JSON and enforce limits on text length, list counts and allowed category identifiers. A caption is not a storage path. A user-supplied MIME label does not establish the file's content type.
Apply authorization before committing the attachment. If a category is tenant-specific, look it up under the authenticated tenant rather than accepting any database identifier. Display stored captions through normal HTML encoding; do not turn them into raw markup when building a preview.
- File policy: allowed formats, size and content validation.
- Metadata policy: required fields, length bounds and allowed values.
- Ownership policy: the current user may attach to this specific record.
- Commit policy: pending uploads are promoted once, with duplicate requests handled safely.
Keep per-file fields attached to the right file
A single caption field outside a multi-file uploader is ambiguous. Store fields per queue item, identify those items consistently and decide what happens when the queue is reordered. Required metadata must be checked before an individual transfer starts and again at the authoritative server boundary.
CoreUpload provides a metadata-fields demo and a Tag Helper configuration surface for per-file values. Use the installed version's metadata format rather than assuming a browser FormData example maps directly to the component's transport. Custom transports and chunk assembly need an explicit rule for when metadata is accepted and finalized.
Handle retries without duplicate records
If a client times out after the bytes arrive, it may retry. Use a server-side upload identifier or idempotency key to connect that retry to the existing pending object. Validate that the retry belongs to the same user and record. Avoid using the original file name as a unique key; two distinct files can share a name.
A metadata edit does not always require re-uploading the bytes. Where your application permits it, update authorized metadata through a separate endpoint and keep that operation subject to the same ownership checks. Expired temporary uploads need a clear response that lets the UI ask for a fresh selection.
Verify the full request and response contract
- Send malformed metadata and confirm an explicit client error.
- Change the target record to one owned by a different user.
- Remove a required per-file value after selecting several files.
- Repeat a completed request and inspect for duplicate attachment rows.
- Check that both stored bytes and stored metadata correspond to the same file.
These checks are more useful than confirming that a success toast appeared. Inspect the persisted result and the authorization boundary, not just the client callback.
Common questions
Can I bind a JSON request body and IFormFile at the same time?
Not as two independent bodies. Use a multipart contract with the file and a JSON text part, or split the operations into explicitly linked requests.
Can the client choose the destination folder?
Treat any destination hint as untrusted. Resolve it against a server-side allowlist or authorized record, rather than accepting an arbitrary filesystem path.
Related guides and working examples
Official references
Examples describe the stated framework and application workflow. Check your installed component version and hosting configuration before adapting them.