only My site

Sunday, August 19, 2007

Handling Custom File Downloads in ASP.NET

We need to set the appropriate MIME content-type and additionally, want to "Force" a download dialog with a custom filename in response to the click event.

void Page_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack){
FileStream MyFileStream = new FileStream(@"d:\inetpub\wwwroot\small.pdf",

FileMode.Open);
long FileSize;
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();


Response.ContentType="application/pdf";
Response.AddHeader( "content-disposition","attachment; filename=MyPDF.PDF");
Response.BinaryWrite(Buffer);


}
}


Imports System
Imports System.Web
Imports System.IO

Namespace LovesPYT

Public Class FileHandling

Shared Public Sub DownloadFile(FilePath as String, Optional
ContentType as String = "")

If File.Exists(FilePath) Then
Dim myFileInfo as FileInfo
Dim StartPos as Long = 0, FileSize as Long, EndPos as Long

myFileInfo = New FileInfo(FilePath)
FileSize = myFileInfo.Length
EndPos = FileSize

HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ClearContent()

Dim Range as String =
HttpContext.Current.Request.Headers("Range")
If Not ((Range Is Nothing) or (Range = "")) Then
Dim StartEnd as Array =
Range.SubString(Range.LastIndexOf("=")+1).Split("-")
If Not StartEnd(0)="" Then
StartPos = CType(StartEnd(0), Long)
End If
If StartEnd.GetUpperBound(0) >= 1 and Not StartEnd(1)="" Then
EndPos = CType(StartEnd(1), Long)
Else
EndPos = FileSize-StartPos
End If
If EndPos > FileSize then
EndPos = FileSize - StartPos
End If
HttpContext.Current.Response.StatusCode=206
HttpContext.Current.Response.StatusDescription="Partial
Content"
HttpContext.Current.Response.AppendHeader("Content-Range",
"bytes " & StartPos &"-"& EndPos & "/" & FileSize)
End If

If Not (ContentType="") and (StartPos = 0) Then
HttpContext.Current.Response.ContentType = ContentType
End If
HttpContext.Current.Response.AppendHeader("Content-disposition",
"attachment; filename=" & myFileInfo.Name)
HttpContext.Current.Response.WriteFile(FilePath, StartPos,
EndPos)
HttpContext.Current.Response.End()
End If

End Sub
End Class
End Namespace


Session redirect Code
Response.AppendHeader("Refresh", Convert.ToString(Session.Timeout * 60) & "; URL=PageExpired.aspx")

Source from http://www.eggheadcafe.com/articles/20011006.asp


No comments: