AI image API download headers: Safe Filenames and Delivery

Nov 18, 2026·10 min read

Your generated product image previews correctly, but clicking Download saves an opaque identifier, opens another browser tab, or returns a file labeled PNG that actually contains an error page. AI image API download headers belong in your application's delivery layer: authorize the requesting tenant, select validated image bytes, and send an accurate media type with a deliberately constructed filename.

This article covers application-owned delivery, meaning responses your backend or controlled storage delivery layer serves after ingestion. It does not describe a GenRelay download-header feature. When integrating the GenRelay image API, keep generation requests separate from your own download policy; do not assume a provider accepts the response headers discussed here as generation parameters.

Which headers should an application send for image downloads?

Send the validated image's Content-Type, an attachment Content-Disposition, and X-Content-Type-Options: nosniff, with caching appropriate to the image's sensitivity. An HTTP response header is metadata sent alongside the response body; it does not transform the body's bytes.

For an authorized response containing validated PNG bytes, a header set could look like this:

Content-Type: image/png
Content-Disposition: attachment; filename="product.png"; filename*=UTF-8''product.png
X-Content-Type-Options: nosniff
Cache-Control: private, no-store

Content-Type identifies the representation's media type. Content-Disposition tells the recipient whether the representation is intended for inline display or download, and can suggest a filename. nosniff asks browsers to respect declared types in relevant request contexts; it is defense in depth, not a file scanner or universal execution barrier.

Use image/jpeg for validated JPEG bytes and image/webp for validated WebP bytes. Do not derive the type from a user-supplied extension. If the server sends Content-Length, calculate it from the exact delivered representation; let the HTTP framework manage it when streaming or compression changes that representation.

How do you validate filenames without accepting paths or header injection?

Treat a download filename as an untrusted display label, reject unsafe input, and require its extension to match the previously validated media type. Header injection means untrusted text introduces unintended header structure, commonly through carriage returns or line feeds.

The following standalone Python standard-library program implements a conservative filename policy. Save it as validate_download_name.py and run python3 validate_download_name.py. It accepts Unicode letters and numbers, spaces, underscores, hyphens, and the single extension separator. It deliberately rejects additional punctuation rather than attempting filesystem-specific cleanup.

import unicodedata
import unittest

EXTENSIONS = {
    "image/png": {"png"},
    "image/jpeg": {"jpg", "jpeg"},
    "image/webp": {"webp"},
}
RESERVED = {"CON", "PRN", "AUX", "NUL"} | {
    f"{prefix}{number}" for prefix in ("COM", "LPT")
    for number in range(1, 10)
}


def validate_filename(name, media_type):
    if not isinstance(name, str) or not name:
        raise ValueError("filename must be nonempty text")
    name = unicodedata.normalize("NFC", name)
    if len(name.encode("utf-8")) > 180:
        raise ValueError("filename exceeds application limit")
    if name != name.strip() or name.count(".") != 1:
        raise ValueError("invalid spacing or extension separator")
    stem, extension = name.rsplit(".", 1)
    if not stem or stem != stem.strip():
        raise ValueError("invalid stem")
    if extension.lower() not in EXTENSIONS.get(media_type, set()):
        raise ValueError("extension does not match validated type")
    if stem.upper() in RESERVED:
        raise ValueError("reserved device name")
    for char in stem:
        category = unicodedata.category(char)
        if not (category[0] in {"L", "N"} or char in " _-"):
            raise ValueError("unsupported filename character")
    return name


class FilenameTests(unittest.TestCase):
    def test_unicode_and_normalization(self):
        self.assertEqual(validate_filename("cafe\u0301.png", "image/png"),
                         "caf\u00e9.png")

    def test_jpeg_extension(self):
        self.assertEqual(validate_filename("Product 2.JPG", "image/jpeg"),
                         "Product 2.JPG")

    def test_reject_unsafe_names(self):
        for name in ("../x.png", "a/b.png", "a\\b.png", "a\r\nb.png",
                     'a"b.png', "a;b.png", "a%0d.png", "a\u202eb.png",
                     "CON.png", "x.png.exe", " x.png", "x .png", ".png",
                     "x\x00.png", "x\t.png", "\u00e9" * 100 + ".png"):
            with self.subTest(name=name), self.assertRaises(ValueError):
                validate_filename(name, "image/png")

    def test_type_mismatch(self):
        for media_type in ("image/jpeg", "text/html", None):
            with self.subTest(media_type=media_type):
                with self.assertRaises(ValueError):
                    validate_filename("x.png", media_type)


if __name__ == "__main__":
    unittest.main()

Unicode normalization puts equivalent text into a consistent representation. Here, NFC means canonical composition. The 180-byte limit is an application choice, not an HTTP standard. Rejecting control and formatting characters also excludes invisible direction-changing characters that can disguise a displayed extension.

This policy trades permissiveness for predictable behavior. Never use the resulting label as a storage path: keep a separate server-generated object identifier. If rejected input needs a replacement, generate a neutral name such as image.png after determining the actual format. Do not silently preserve suspicious fragments.

How do you construct Content-Disposition for UTF-8 filenames?

Emit a restricted ASCII filename fallback plus a percent-encoded UTF-8 filename* value, after validation. ASCII is the basic character set used by the fallback. UTF-8 encodes Unicode text, while RFC 5987 defines the extended parameter syntax used here to carry that text in an ASCII header value.

This second independent standard-library program constructs headers from an already validated canonical label. Save it as download_disposition.py and run python3 download_disposition.py. In your application, call the first program's validator before this constructor; this example does not authorize requests or inspect image bytes.

import re
import unicodedata
import unittest
from urllib.parse import quote, unquote


def content_disposition(validated_name):
    # Defense in depth; full filename policy runs before this function.
    if not isinstance(validated_name, str) or not validated_name:
        raise ValueError("validated filename required")
    if any(unicodedata.category(c).startswith("C")
           for c in validated_name):
        raise ValueError("control or formatting character")
    if any(c in validated_name for c in '/\\";'):
        raise ValueError("unexpected delimiter")
    if validated_name.count(".") != 1:
        raise ValueError("expected one extension separator")
    stem, extension = validated_name.rsplit(".", 1)
    extension = extension.lower()
    if not stem or extension not in {"png", "jpg", "jpeg", "webp"}:
        raise ValueError("unsupported image filename")
    ascii_stem = unicodedata.normalize("NFKD", stem)
    ascii_stem = ascii_stem.encode("ascii", "ignore").decode("ascii")
    ascii_stem = re.sub(r"[^A-Za-z0-9_-]+", "-", ascii_stem)
    ascii_stem = ascii_stem.strip("-_")[:60] or "image"
    fallback = f"download-{ascii_stem}.{extension}"
    encoded = quote(validated_name, safe="", encoding="utf-8", errors="strict")
    return f'attachment; filename="{fallback}"; filename*=UTF-8\'\'{encoded}'


class DispositionTests(unittest.TestCase):
    def test_ascii(self):
        self.assertEqual(content_disposition("product.png"),
                         'attachment; filename="download-product.png"; '
                         "filename*=UTF-8''product.png")

    def test_utf8_round_trip(self):
        header = content_disposition("\u590f\u65e5 \u6d77\u62a5.png")
        header.encode("ascii")
        self.assertIn('filename="download-image.png"', header)
        encoded = header.split("filename*=UTF-8''", 1)[1]
        self.assertEqual(unquote(encoded), "\u590f\u65e5 \u6d77\u62a5.png")
        self.assertIn("%20", encoded)

    def test_ascii_transliteration(self):
        self.assertIn('filename="download-cafe.jpeg"',
                      content_disposition("caf\u00e9.jpeg"))

    def test_reject_header_injection(self):
        for name in ('a\r\nInjected.png', 'a"b.png', 'a;b.png',
                     'a/b.png', 'a\\b.png', 'a\u202eb.png'):
            with self.subTest(name=name), self.assertRaises(ValueError):
                content_disposition(name)


if __name__ == "__main__":
    unittest.main()

The download- prefix keeps fallback names away from bare reserved device names. quote, rather than form encoding, produces %20 for spaces. The extended parameter is not wrapped in quotes. Supporting clients prefer it; clients that ignore it can use the ASCII fallback. These suggested names do not control where a user saves a file.

Where should tenant authorization happen before serving an image?

Authorize the authenticated principal against the asset's tenant and access policy before opening storage, returning bytes, or issuing a download link. A tenant is the organizational boundary separating one customer's data from another's. Knowing an asset identifier does not establish permission to read it.

Use this application-owned sequence:

  1. Authenticate the requester and derive tenant membership from trusted session data.
  2. Resolve the asset through a tenant-scoped record lookup; check sharing rules and deletion state.
  3. Select the validated stored object and its recorded media type.
  4. Validate the requested display name and build the download headers.
  5. Stream the authorized representation and record the access decision without logging credentials.

Do not accept a storage key, tenant identifier, or arbitrary fetch URL as proof of ownership. Avoid revealing whether another tenant's asset exists through different error details. Test that switching the asset identifier cannot retrieve another customer's bytes or produce a valid download link.

A signed URL is a URL containing a time-limited authorization credential. If your application issues one, the permission decision precedes issuance; possession may permit access until expiry under that delivery system's policy. The signed URL guide covers that separate design. Header parameters in such URLs require explicit support from your storage service, not assumptions about GenRelay.

How can you prevent correctly named downloads from containing invalid bytes?

Validate the stored representation before delivery and derive its type from trusted inspection, not upstream labels or filenames. A response labeled image/png can still contain an HTML error document. A signature check identifies candidate formats but does not establish that a complete image decodes safely.

At ingestion, enforce size limits, inspect the format, and decode with a maintained image library under resource limits. Record the approved media type with the exact immutable object version. The standard-library examples above intentionally test filenames and header construction, not image decoding. Use the output validation guide for that earlier boundary.

For private downloads, prevent shared caches from mixing tenant responses; private, no-store is a conservative starting policy. A content delivery network, or CDN, is a distributed caching layer: inspect its actual configuration rather than assuming it honors every application decision. Verify the final response after redirects and edge processing, since storage metadata can replace intended headers.

Why does the browser still display the image instead of saving it?

The final response may lack Content-Disposition: attachment, or navigation may reach a different response after a redirect. Inspect the browser network panel for the actual image response, not the generation response. Client-side download attributes and browser preferences can also affect behavior; test the supported browser flow.

Can JavaScript read Content-Disposition from another origin?

JavaScript needs appropriate cross-origin resource sharing configuration and Access-Control-Expose-Headers: Content-Disposition to read that header from an authorized cross-origin response. Cross-origin resource sharing, or CORS, controls browser access to responses across origins. It does not replace tenant authorization, and exposing a header does not grant access to the underlying asset.

Is attachment delivery sufficient for SVG images?

No: attachment delivery is not a complete policy for active image formats such as SVG. SVG can contain scripts or external references depending on how it is used. The examples intentionally restrict delivery to PNG, JPEG, and WebP; support SVG through a separate reviewed sanitization or rasterization pipeline.

Should the application trust a filename returned with a generation result?

No: treat every suggested filename as untrusted input, including names received from external services. Validate the label, bind its extension to inspected bytes, and retain your server-owned storage identifier. Generation success and safe download delivery are separate application responsibilities.

Related posts

Join our DiscordAI image API download headers: Safe Filenames and Delivery — GenRelay