How to set name of file downloaded from browser?

Sparafusile picture Sparafusile · Jun 23, 2010 · Viewed 73.4k times · Source

I'm writing a web application that, among other things, allows users to upload files to my server. In order to prevent name clashes and to organize the files, I rename them once they are put on my server. By keeping track of the original file name I can communicate with the file's owner without them ever knowing I changed the file name on the back end. That is, until they go do download the file. In that case they're prompted to download a file with a unfamiliar name.

My question is, is there any way to specify the name of a file to be downloaded using just HTML? So a user uploads a file named 'abc.txt' and I rename it to 'xyz.txt', but when they download it I want the browser to save the file as 'abc.txt' by default. If this isn't possible with just HTML, is there any way to do it?

Answer

Palantir picture Palantir · Jun 23, 2010

Can't find a way in HTML. I think you'll need a server-side script which will output a content-disposition header. In php this is done like this:

header('Content-Disposition: attachment; filename="downloaded.pdf"');

if you wish to provide a default filename, but not automatic download, this seems to work.

header('Content-Disposition: filename="filetodownload.jpg"');

In fact, it is the server that is directly serving your files, so you have no way to interact with it from HTML, as HTML is not involved at all.