About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).
Showing posts with label download. Show all posts
Showing posts with label download. Show all posts

Friday, August 24, 2007

File Download in ASP.Net

Ok, so I'm making my own site and what I am doing is allowing users on my website to upload and download files. These files are placed into my sql-server database. I was having trouble getting the Response.Write to work, so I went to Response.OutputStream.Write instead.

So on my download page I have:

protected void Page_Load(object sender, EventArgs e)
{
String filepath =
Request.Params.Get("Author") + "-" + Request.Params.Get("Title") + ".mp3";
if
(filepath.Length != 0)
{
Stream readStream =
MusicManager.GetSong(Int32.Parse(Request.Params.Get("file")));
int Length =
256;
Response.Clear();
Response.ContentType =
"application/octet-stream";
Response.AddHeader("Content-Disposition",
"attachment; filename=\"" + filepath + "\"");
Response.Flush();
Byte[]
buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0,
Length);
while (bytesRead > 0)
{
Response.OutputStream.Write(buffer,
0, bytesRead);
bytesRead = readStream.Read(buffer, 0,
Length);
}
Response.End();
readStream.Close();
}
}



Of course I have a page that sends in the query string with the necessary info

This seems all simple when it starts working, but it took me 2 hours to get the file to download correctly.