时间:2021-07-01 10:21:17 帮助过:15人阅读
Shared Function DownloadFile(ByVal WebForm As System.Web.UI.Page, ByVal FileNameWhenUserDownload As String, ByVal FileBody As String)
WebForm.Response.ClearHeaders()
WebForm.Response.Clear()
WebForm.Response.Expires = 0
WebForm.Response.Buffer = True
WebForm.Response.AddHeader("Accept-Language", "zh-tw")
'文件名称
WebForm.Response.AddHeader("content-disposition", "attachment; filename=" & Chr(34) & System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8) & Chr(34))
WebForm.Response.ContentType = "Application/octet-stream"
'文件内容
WebForm.Response.Write(FileBody)
WebForm.Response.End()
End Function
上面这段代码是下载一个动态产生的文本文件,若这个文件已经存在于服务器端的实体路径,则可以通过下面的函数:
代码如下:
Shared Sub DownloadFile(ByVal WebForm As System.Web.UI.Page, ByVal FileNameWhenUserDownload As String, ByVal FilePath As String)
WebForm.Response.ClearHeaders()
WebForm.Response.Clear()
WebForm.Response.Expires = 0
WebForm.Response.Buffer = True
WebForm.Response.AddHeader("Accept-Language", "zh-tw")
'文件名称
WebForm.Response.AddHeader("content-disposition", "attachment; filename=" & Chr(34) & System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8) & Chr(34))
WebForm.Response.ContentType = "Application/octet-stream"
'文件内容
WebForm.Response.Write(System.IO.File.ReadAllBytes(FilePath))
WebForm.Response.End()
End Sub
上面这两个下载文件的的函数,应可解决大多数开发人员在ASP.NET当中的文件下载问题。