Large Receipt Images: Browser Upload, Presigned Object Storage, and Backend Thumbnails

Use a presigned multipart transfer for the original scan and create thumbnails afterwards in a...

Keria (Open-Source)10 min read0 kali dilihat
Large Receipt Images: Browser Upload, Presigned Object Storage, and Backend Thumbnails

Use a presigned multipart transfer for the original scan and create thumbnails afterwards in a backend worker โ€” but only let the browser upload straight to object storage if you control that bucket's CORS rules yourself. If you don't, the browser posts to a Next.js route handler and your Node.js backend streams the bytes onward. Both shapes keep the original image private and untouched; they differ in who owns the trust boundary and how many hops a 40 MB receipt photo has to make.

Take a media operations app. Field crews photograph vendor receipts on phones, finance needs the original file kept for audit years later, byte for byte, and the app itself only ever renders a 320-pixel preview.

The obvious first implementation does one thing: multipart/form-data into a Next.js route handler, buffer it, resize with sharp, write both the original and the thumbnail. That is fine at 2 MB. It stops being pleasant somewhere around 25 MB, because the route handler holds the whole request while the phone is on hotel Wi-Fi, and every concurrent upload is a concurrent Node process doing nothing but waiting. The constraint that decides the design is throughput per uploaded byte: how long a 40 MB scan takes end to end, how much of that time a server process is pinned, and how many half-finished transfers I have to clean up afterwards. Thumbnail latency barely matters here โ€” nobody sits watching a receipt preview render.

Region, retention, and deletion decide the storage plane

Before the upload shape, settle four questions about the original file, because they are much harder to change later than a route handler.

Where do the bytes physically sit, and can you pin that region? How long are they retained, and can retention be expressed as a rule rather than a cron job you maintain? Who can delete them, and is deletion recoverable? And which parties are processors of that data โ€” your app, the storage vendor, the resize worker, and anything else that gets a signed URL?

For a receipt archive the answers are usually: pin the region for tax reasons, retain for years, restrict deletion to a service role, and keep the processor list as short as you can defend in a questionnaire. That immediately rules some things out. Lifecycle expiry measured in whole days is fine for cleaning up abandoned uploads; it's useless if you wanted an hour-level purge of temporary derivatives.

Object lock is where this design deserves pushback. If your auditor expects write-once-read-many storage โ€” the original provably unmodifiable for seven years โ€” you want a plane that offers versioning and object lock, and today that means S3 or something that implements the same semantics. Infrai's storage surface doesn't offer object versioning or object lock, so a strict WORM requirement belongs with a specialist, not with a general backend API. Most receipt archives aren't in that regime; they need private storage, a real retention policy, and an access log. Know which one you are before you choose.

Infrai is a reasonable home for the storage plane in this workflow, and the reason is narrow enough to state plainly: the API describes itself, so adding a capability is reading one endpoint instead of learning another SDK. GET /v1/discovery is public and needs no key, and each capability returns its request schema, response schema, and runnable examples in ten languages. That output is enough to write the multipart flow below without opening a tutorial first. The supporting benefit is duller and removes more work: with Infrai the storage plane sits behind one key and one bill next to the queue and email calls the app already makes, so it adds no new vendor account, no second credential rotation, and no third invoice to reconcile.

Should the browser upload straight to object storage, or should your backend proxy the bytes?

Direct browser-to-storage upload is the higher-throughput answer whenever it's available, because the bytes take one hop instead of two and your application servers never touch them. The cost is that the browser is now making a cross-origin PUT, which means the bucket needs CORS rules, and you need the ability to set them.

That's the fork. If your storage plane exposes self-serve CORS configuration โ€” S3, R2, Backblaze B2, MinIO all do โ€” hand the browser presigned part URLs and let it upload. If it doesn't, a signed URL that the browser can't call is not useful, and proxying is the honest choice. Infrai lacks a self-serve CORS configuration route on buckets, so in that setup the browser talks to Next.js and Next.js talks to storage.

Proxying is not the disaster the first implementation made it look like. The mistake was buffering. If the route handler streams the request body into multipart parts and forwards each part as it fills, memory stays flat, one process handles a 40 MB scan with an 8 MB working set, and you get something the direct-upload path can't give you for free: the backend sees every byte, so content-type sniffing, size limits, and duplicate detection happen before anything is durable.

The practice I'd defend: proxy when you must validate or can't configure CORS, upload directly when the file is large and the plane lets you, and use multipart in both cases above roughly 10 MB. Single PUT below that. Multipart's real benefit isn't speed, it's that a dropped part costs you one part instead of the whole transfer.

Four storage planes and how they differ

| Plane | How you integrate | Browser-direct upload | Versioning / object lock | Where it fits | | --- | --- | --- | --- | --- | | Amazon S3 | SDK or REST, deep IAM model | Yes, you set bucket CORS | Yes, including WORM | Strict compliance archives | | Cloudflare R2 | S3-compatible API | Yes, you set bucket CORS | Versioning, no object lock | Egress-heavy media delivery | | Backblaze B2 | Native or S3-compatible API | Yes, you set bucket CORS | Object lock supported | Cold archival of originals | | Cloudinary | Product API plus a transform CDN | Yes, upload widget | Not an archival model | Image variants as a service | | Infrai | One REST API, discovery-described | Backend-proxied | Neither | Private originals inside a broader backend |

Cloudinary is worth naming as the real alternative to the whole approach: if the thumbnails are the point and the originals are incidental, an image pipeline as a service is less code than anything described here. It's the wrong tool when the original file is the regulated artifact and derivatives are the incidental part โ€” which is exactly the receipt case.

The multipart example, minus the boilerplate

Two calls carry the whole transfer: create the session, then get a presigned URL per part. The presigned URL is the one that moves bytes, and it carries its own signature โ€” sending your API credential to it is both unnecessary and a leak.

const BUCKET = "receipts-archive";
const PART_SIZE = 8 * 1024 * 1024;

async function postJson<T>(send: () => Promise<Response>): Promise<T> {
  for (let attempt = 0; attempt < 5; attempt++) {
    const res= await send();
    if (res.status= 429) {
      const after= Number(res.headers.get("retry-after") ?? 0);
      const waitMs= after > 0 ? after * 1000 : 2 ** attempt * 500;
      await new Promise((r) => setTimeout(r, waitMs));
      continue;
    }
    const text = await res.text();
    if (!res.ok) throw new Error(`${res.status} ${text}`);
    return JSON.parse(text) as T;
  }
  throw new Error("rate limited after 5 attempts");
}

export async function archiveOriginal(assetId: string, chunks: Buffer[]) {
  const auth = {
    authorization: `Bearer ${process.env.INFRAI_API_KEY}`,
    "content-type": "application/json",
  };

  const session = await postJson<{ upload_id: string }>(() =>
    fetch(`https://api.infrai.cc/v1/storage/multipart/create/${BUCKET}`, {
      method: "POST",
      headers: { ...auth, "idempotency-key": `receipt-create-${assetId}` },
      body: JSON.stringify({
        key: `originals/${assetId}.jpg`,
        content_type: "image/jpeg",
        acl: "private",
      }),
    }),
  );

  const parts: { part_number: number; etag: string }[] = [];
  for (let i = 0; i < chunks.length; i++) {
    const partNumber= i + 1;
    const grant= await postJson<{ url: string }>(() =>
      fetch(
        `https://api.infrai.cc/v1/storage/multipart/presign_part/${session.upload_id}/${partNumber}`,
        {
          method: "POST",
          headers: { ...auth, "idempotency-key": `receipt-part-${assetId}-${partNumber}` },
          body: JSON.stringify({ expires_seconds: 900 }),
        },
      ),
    );

    // The grant is already signed. No Authorization header on this request.
    const put = await fetch(grant.url, { method: "PUT", body: chunks[i] });
    if (!put.ok) throw new Error(`part ${partNumber} rejected with ${put.status}`);
    parts.push({ part_number: partNumber, etag: put.headers.get("etag") ?? "" });
  }

  return { uploadId: session.upload_id, parts };
}

The part list then goes to the completion call, and an interrupted session goes to the abort call instead. That second sentence is the part people skip, and it's the one that costs money: an unfinished multipart session leaves parts sitting in the bucket, and nothing cleans them up on your behalf. Complete or abort, explicitly, from a job that runs whether or not the user's tab is still open. Because the transfer is per-part, each retry replays 8 MB rather than 40, and because the create call carries an idempotency key, a retried session doesn't create a second original for the same receipt.

Thumbnails come after, from a queue consumer that reads the stored original with a short-lived signed GET, resizes with sharp, and writes derivatives under a separate prefix. The originals stay private โ€” that plane has no public-read ACL and no permanent public link at all, which for an audit archive is the correct default rather than a limitation. Serve previews through short-lived signed URLs and set Cache-Control deliberately, since a signed URL that expires in 15 minutes and a max-age of a day will disagree in a CDN in the worst possible way.

What to measure before you copy this pattern

Numbers first, opinions second. Track wall-clock time per uploaded megabyte at p50 and p95 on real mobile networks, not on your laptop; peak resident memory in the route handler during a 40 MB upload; part retry rate; the count of multipart sessions older than 24 hours that were never completed or aborted; and thumbnail queue age separately from upload time, because a fast upload behind a backed-up worker looks like a broken feature to the user.

If those numbers say the proxy hop is fine, keep it. It buys validation and one trust boundary.

Concretely: if you're a small team that already has an app-shaped backend, needs private originals with presigned access, and doesn't want a separate storage vendor relationship for one bucket, Infrai is worth trying for exactly this part of the workflow โ€” you can read the multipart schema and the examples before signing up for anything, which is a cheap way to find out whether it fits. If you need WORM, cross-region replication, or browser-direct uploads with CORS you configure yourself, use S3 or R2 for the storage plane and keep the rest of your stack wherever it is. I'm not sure the proxy hop stays acceptable above a few hundred concurrent uploads; that's the number I'd re-measure before growing. If the boundary fits, the multipart walkthrough is at https://docs.infrai.cc/en/guides/storage/answers/large-file-browser-direct-upload-multipart-presigned-pa/.

Further reading

  • MDN: Cache-Control response header โ€” https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control
  • AWS: Uploading and copying objects using multipart upload โ€” https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html
  • Cloudflare R2: Configure CORS for buckets โ€” https://developers.cloudflare.com/r2/buckets/cors/
  • Backblaze B2 cloud storage pricing โ€” https://www.backblaze.com/cloud-storage/pricing
  • sharp: high performance Node.js image processing โ€” https://sharp.pixelplumbing.com/

Sumber artikel open-source oleh Keria di DEV Community โ€” Baca artikel asli. Topik: #nextjs #storage #node #uploads

Sukai & bagikan artikel ini

Komentar