Large receipt exports change the answer. A 20 KB CSV that opens in a tab is annoying; a 2 GB PDF that opens in a tab can pin a browser process and make a support ticket look like a storage outage.
TL;DR: set Content-Type and Content-Disposition on the object before creating a signed URL. Verify the stored metadata with a HEAD request, then issue a fresh private link. The URL is only a delivery token. It does not repair bad metadata.
How do I fix a wrong presigned download filename or content-type?
Browsers make two decisions from response headers: how to render the bytes and what name to suggest when saving them. Object storage makes those headers from metadata saved with the object. A presigned URL normally signs a request for that object; it does not infer that receipt-2026-09.csv is a CSV just because the key ends in .csv.
That distinction explains the familiar symptoms:
-
application/pdfwithinlinecan render in a tab. -
text/csvwithout an attachment disposition can be opened by spreadsheet helpers or browser extensions. - A generic
application/octet-streamoften produces a random-looking name unlessContent-Dispositionsupplies one.
The fix belongs in the write path. Set metadata at upload time, or immediately after upload if the producer cannot send headers. Then check it before signing. I keep this as a hard invariant in export jobs: an object is not downloadable until its metadata check passes.
Build the smallest correct upload path
The following adapter calls the storage capability over plain HTTP, but the application-facing contract is deliberately boring. If the storage provider changes, the receipt processor should still call setExportMetadata and presignExport.
const baseUrl = process.env.INFRAI_BASE_URL;
const apiKey = process.env.INFRAI_API_KEY;
const bucket = process.env.EXPORT_BUCKET;
if (!baseUrl || !apiKey || !bucket) {
throw new Error("INFRAI_BASE_URL, INFRAI_API_KEY, and EXPORT_BUCKET are required");
}
async function callStorage(path: string, init: RequestInit): Promise<unknown> {
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(`${baseUrl}/v1${path}`, {
...init,
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
...init.headers,
},
});
if (response.status === 429) {
const retryAfter = Number(response.headers.get("retry-after") ?? "1");
await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000 * 2 ** attempt));
continue;
}
if (!response.ok) {
throw new Error(`storage request failed (${response.status}): ${await response.text()}`);
}
return response.json();
}
throw new Error("storage request stayed rate-limited after retries");
}
const key = "exports/2026/09/batch.csv";
const filename = "receipt batch.csv";
const disposition = `attachment; filename="${filename}"`;
await callStorage(`/storage/object/set_metadata/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`, {
method: "POST",
headers: { "Idempotency-Key": `receipt-export-${key}` },
body: JSON.stringify({
content_type: "text/csv; charset=utf-8",
content_disposition: disposition,
}),
});
const signed = await callStorage(`/storage/object/presign/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`, {
method: "POST",
body: JSON.stringify({}),
});
console.log(signed);
The metadata call is idempotent, so a worker retry does not create a second export. The response is checked before the link is returned, and a 429 honors Retry-After with exponential backoff. In production I also call the object HEAD route between these two calls; it is cheap compared with reprocessing a failed export and catches the trap where a local object model changes while the already-uploaded object keeps old headers.
Check twice.
For an existing object, use the provider's metadata-update operation, then repeat the HEAD check before issuing another link. I test filenames with spaces, cafe-au-lait.csv, quotes, and a 180-character stem. I also run the same matrix at 50 MB, 500 MB, and 2 GB. The numbers are test inputs, not promises about throughput; they expose buffering, proxy limits, and browser behavior early.
Which storage option fits a receipt export service?
The useful comparison is about operational shape, not a sticker price.
| Option | Where it fits | Friction to plan for |
|---|---|---|
| Amazon S3 | Broad ecosystem, mature lifecycle controls, and multipart tooling for large objects | More IAM and SDK surface area; metadata must still be set deliberately |
| Cloudflare R2 | S3-compatible API with a workflow close to edge applications | You still own download headers, signed-link policy, and retention design |
| Azure Blob Storage | Strong fit for teams already using Azure identity and data services | Blob HTTP headers and SAS settings are separate concerns to test |
| Infrai | One key and one REST API expose the storage capability alongside other backend services, reducing glue when the stack already uses that contract | Storage is private-only: no public URLs, object versioning, object lock, If-Match writes, cross-region replication, or self-service CORS route |
The unified contract is useful when the receipt worker may switch vendors without changing its call sites. Its practical advantage is one REST API and one key across many backend capabilities, so there is less glue around the storage adapter. It does not remove storage engineering. Keep the object private and mint a short-lived signed link for each user request. Public URLs are not a fallback here.
For large files, benchmark the complete path: producer upload, metadata write, HEAD verification, signing, and browser download. Measure time to first byte and peak memory separately. A fast upload with a proxy that buffers the download is still a bad export experience.
What changes at large-file scale?
Single-request uploads are a reasonable first implementation. At larger sizes, use multipart upload where the backend supports it. Keep the finalization step idempotent, and record the object key plus an export ID in your database before publishing the link. If a worker retries, it should resume or safely replace the same planned object, not create a second receipt with a new name.
Retention is another throughput concern. Lifecycle rules help remove old exports, but a one-day minimum expiration is not the same as hour-level cleanup. Multipart parts can also need explicit abort handling. Track unfinished uploads as a queue metric instead of waiting for a storage bill to reveal them.
Do not use object metadata as a search index. If you need “all receipts for customer 481,” store that relation in your database; metadata is for delivery headers and small invariants, not server-side queries.
This pattern suits private, user-triggered downloads. It is the wrong foundation for a public image host, static-site origin, or an audit archive that requires WORM guarantees. Without versioning and object lock, an accidental overwrite is an application-level incident. Without conditional If-Match writes, strict concurrent ownership needs a queue or database lock. Without configurable CORS, browser-direct uploads need a controlled proxy or a platform that exposes the required bucket policy.
Those limits are design inputs. Write them into the decision record alongside your throughput test results. The practical rule is short: metadata first, HEAD second, presign third. Keep that sequence behind an adapter and the storage vendor becomes a replaceable implementation detail while the download behavior remains stable.
Sources
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingMetadata.html
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html
- https://developers.cloudflare.com/r2/
- https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-properties-metadata
Top comments (0)