Skip to content

Instantly share code, notes, and snippets.

@evagoras
Created September 28, 2023 14:01
Show Gist options
  • Save evagoras/c3586ce2846ca8743eef4a892f412226 to your computer and use it in GitHub Desktop.
Save evagoras/c3586ce2846ca8743eef4a892f412226 to your computer and use it in GitHub Desktop.
Downloading any file to the browser – Part II: using ASP.NET
<a href="download.aspx?file=/images/logo.gif">Download the logo image</a>
<%@ Page language="vb" runat="server" explicit="true" strict="true" %>
<script language="vb" runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Dim strRequest As String = Request.QueryString("file") '-- if something was passed to the file querystring
If strRequest <> "" Then 'get absolute path of the file
Dim path As String = Server.MapPath(strRequest) 'get file object as FileInfo
Dim file As System.IO.FileInfo = New System.IO.FileInfo(path) '-- if the file exists on the server
If file.Exists Then 'set appropriate headers
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name)
Response.AddHeader("Content-Length", file.Length.ToString())
Response.ContentType = "application/octet-stream"
Response.WriteFile(file.FullName)
Response.End 'if file does not exist
Else
Response.Write("This file does not exist.")
End If 'nothing in the URL as HTTP GET
Else
Response.Write("Please provide a file to download.")
End If
End Sub
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment