Plain curl -O names the file after the last part of the URL. That works for /files/report.pdf, and gives you a file called download?id=4812 for the many sites that serve files through a script. The browser gets the proper name from a header, and curl can do the same.
Add -J (--remote-header-name) to -O. curl then uses the filename from the server’s Content-Disposition header instead of the URL:
curl -L -OJ --output-dir ~/Downloads "https://example.com/download?id=4812"
If the server answers with Content-Disposition: attachment; filename="report-2026.pdf", you end up with ~/Downloads/report-2026.pdf. The -L follows redirects, which download links almost always use, and --output-dir picks the folder (it has to exist, unless you add --create-dirs). When the server sends no filename at all, -J does nothing and curl falls back to the name from the URL. Since curl 8.19.0 it first tries the name from the last redirect.
There are a few things to know. With -J, curl refuses to overwrite a file that already exists and stops with an error, unless you add --clobber. Any path in the server’s filename is stripped off, so it can’t write outside your folder. But curl doesn’t decode %20 and friends in the name, and it only reads the plain filename field, not filename*, so names with special characters can come out odd.
My bigger caveat is trust. You’re letting a server pick a filename on your disk. The curl docs warn about this explicitly, especially on Windows, where a rogue server could hand you a DLL name that other software loads. I’d only use -J on sites I trust and look at what landed before opening it.
Further reading: curl man page: –remote-header-name