Tags
.NET, attachment, C#, contentType, download, Response, Stream
Pushing a file to the user to download with a programmatically generated name in ASP.NET
by Wayne Denier on November 3rd, 2009
I’ve been saving the files that I am receiving via user uploads with a unique identifier as the name (ie. 8b8c9145-1ce1-4cd1-99a7-fc57871b5671.pdf) so we don’t receive collisions with like named files. Here’s how I rewrite the filename to its’ original name (loaded from the database) before sending it back to the user. Using this you can make up any appropriate file name (ie UserReport_CurrentDate.xls).
// Load the physical file into a byte array
byte[] byteArray = new byte[file.Size];
System.IO.Stream stream = file.GetFile();
stream.Read(byteArray, 0, file.Size);
stream.Close();
// Push the byte array to the user as a download
context.Response.BinaryWrite(byteArray);
context.Response.ContentType = file.MimeType;
context.Response.AddHeader("content-disposition", "attachment;filename=" + context.Server.UrlEncode(file.FileName));
From → C#, Development, Web Development
No comments yet