View Single Post
Old 12-09-2015, 10:13 AM
YaskinForrit YaskinForrit is offline
Join Date: Feb 2009
Posts: 6
Default ASP.Net download issue

My ASP.Net page contains several tabs, each with a drop down list that contains files available for download.

I am using a separate page (DownloadFile.ashx) to handle the download and calling it with Response.Redirect.

Download Function
Public Shared Sub DownloadFile(ByVal FileURL As String)
Dim fileName As String

    'Get full fileURL if leading character is '~' or '.'
    If FileURL.Substring(0, 1) = "~" Or FileURL.Substring(0, 1) = "." Then
        FileURL = New System.IO.FileInfo(HttpContext.Current.Server.MapPath(FileURL)).FullName
    End If

    'Pass file URL to Document.aspx 
    System.Web.HttpContext.Current.Response.Redirect("Document.aspx?fileURL=" & FileURL.ToString())
End Sub
DownloadFile.ashx Page_Load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
Dim request As System.Web.HttpRequest = System.Web.HttpContext.Current.Request
Dim fileURL As String = ""
Dim fileName As String = ""
Dim fileType As String = ""
Dim contentType As String = "text/plain"

	fileURL = request.QueryString("fileURL").ToString()
	fileName = fileURL.Substring(fileURL.LastIndexOf("/") + 1)
	fileType = fileName.Substring(fileName.LastIndexOf(".") + 1).ToUpper

	'get content type from file type
	Select Case fileType
	  Case "PDF"
		contentType = "application/pdf"
	  Case "PNG"
		contentType = "image/png"
	  Case "JPG"
		contentType = "image/jpeg"
	  Case "HTML", "HTM"
		contentType = "text/html"
	  Case "XLSX", "XLS"
		contentType = "application/vnd.xls"
	  Case "DOCX", "DOC"
		contentType = "application/ms-word"
	End Select

	If Not fileName Is Nothing Then
	  response.ContentType = contentType
	  response.AddHeader("Content-Disposition", "attachment; filename=" & fileName & ";")
	End If
End Sub
I have tried using HTTPApplication.CompleteRequest instead of Response.End and I have even tried moving the DownloadFile.ashx code into my download function.

The error remains the same.

My download works but then every time I get postback, it causes the file to be re-downloaded.
Reply With Quote