Issue with commas in LazyMedia filenames when downloaded

What I’m trying to do:

Download a LazyMedia object — e.g. a Media stored in and retrieved from a Data Table — whose filename contains a comma, using anvil.media.download().

What I’ve tried and what’s not working:

When the Media’s name contains a comma, the downloaded file’s name is truncated at the first comma, and everything after it is dropped — including the file extension. A Media named Report, final.xlsx downloads as a file called Report with no extension, which the OS then treats as an unrecognized file type. The file contents are fine; it’s just the name.

I (aka mostly Claude) went digging through anvil-runtime to try to understand it, and as best I can tell it traces back to serve-lazy-media — the handler behind the /_/lm/... endpoint that anvil.media.download() uses for LazyMedia. It builds the Content-Disposition header by interpolating the media name directly, without quoting or encoding it, at server.clj#L98-L100:

(resp/header "Content-Disposition" (if nodl nil (str "attachment"
                                                     (when-let [name (.getName ^MediaDescriptor m)]
                                                       (str ";filename=" name)))))

For a media named Report, final.xlsx that produces:

Content-Disposition: attachment;filename=Report, final.xlsx

My understanding is that the filename value needs to be a token or a quoted-string, and an unquoted value containing a comma (or space, ;, etc.) isn’t valid — which would explain why the browser stops reading the name at the comma. I haven’t confirmed exactly how each browser handles it, but the truncation point lines up.

For what it’s worth, a couple of other places in the runtime already quote/encode the filename — the HTTP-endpoint media response at serve_app.clj#L482 wraps it in quotes and URL-encodes it, and the SAML metadata download at server.clj#L283 strips special characters first. So it may just be a matter of applying similar handling on the lazy-media path, but obviously you guys will know what’s best.

This also looks like it might be the same issue as this thread from May 2024: Commas in filename - bug in Chrome.

I’m sure there’s context I’m missing about why it’s written this way, but I figured the trace might be a helpful starting point. Thanks!

1 Like

thanks we’ll take a look

1 Like