I have a asp.net page that allows a user to upload a file. In order to guarantee a user can't overwrite another user's file that happens to be named the same I rename the files as I upload them to be unique (for instance SessionId + DateTime.Ticks). On another page, users get a link to the file for download. Having a unqiqeuly named file may be conveinent for the server, but it's not very good for the user so I had to come up with a way to return the file to the browser with the original file name. I wrote a simple aspx page that acts as a download handler and simply writes the file to the browser as a octet-stream, but I modify the headers so it sends the correct name:
private void Page_Load(object sender, System.EventArgs e)
{
Response.ContentType = @"application\octet-stream";
Response.AddHeader( "Content-Disposition", "inline; filename=" + "somefile.ext");
Response.WriteFile("c:\inetpub\wwwroot\mysite\files\0001234.0001234");
Response.Flush();
Response.End();
}
My .aspx page is empty except for the @page declaration. The trick comes with the Reponse.AddHeader("Content-Disposition", “inline; filename=somefilename.ext“), which forces the browser to raise a file download dialog box and allows you to specify the file's name independant of the actual file name stored on the server.
Optionally, you could get around all of this by creating a new, unique directory name for every file the user uploads, that way you could preserve filenames and never worry about overwritting files. However, the technique above allows far more flexibility for security or other proccessing.
Resources: