ASP.Net 文件下载(VB.Net)
直接下载WriteFile
Dim fileName As String = TFlnm.Text ' 客户端保存的文件名,可以通过Textbox输入
Dim filePath As String = TPath.Text '/路径
Dim fileInfo As FileInfo = New FileInfo(filePath)
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName)
Response.AddHeader("Content-Length", fileInfo.Length.ToString())
Response.AddHeader("Content-Transfer-Encoding", "binary")
Response.ContentType = "application/octet-stream"
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312")
Response.WriteFile(fileInfo.FullName)
Response.Flush()
Response.End()
Exit Sub
这个主要弊端就是遇到百兆的大文件,经常内存溢出错误这个好像和服务器自身配置有关系。我两台电脑同样使用IIS Express一个高配的报错,一个低配的反而正常,总之就是不好使。
以字符流的形式下载文件
Dim fileName As String = TFlnm.Text ' 客户端保存的文件名,可以通过Textbox输入
Dim filePath As String = TPath.Text '/路径
Dim fs As FileStream = New FileStream(filePath, FileMode.Open)
Dim bytes(fs.Length) As Byte
fs.Read(bytes, 0, bytes.Length)
fs.Close()
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8))
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
大文件下载测试通过
分段下载
我也记不清从哪里看的
Dim fileName As String = TFlnm.Text ' 客户端保存的文件名
Dim filePath As String = TPath.Text
Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(filePath)
If fileInfo.Exists = True Then
Const ChunkSize As Long = 102400 ' 100K 每次读取文件, 只读取100K, 这样可以缓解服务器的压力
Dim buffer(ChunkSize) As Byte
Response.Clear()
Dim iStream As System.IO.FileStream = System.IO.File.OpenRead(filePath)
Dim dataLengthToRead As Long = iStream.Length '//获取下载的文件总大小
'Response.Write("<script>alert(iStream.Length)</script>")
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName))
While (dataLengthToRead > 0 And Response.IsClientConnected)
Dim lengthRead As Integer = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize)) '//读取的大小
Response.OutputStream.Write(buffer, 0, lengthRead)
Response.Flush()
ataLengthToRead = dataLengthToRead - lengthRead
End While
Response.Close()
End If
这个下载Rar压缩包还可以,但是下载文件就损坏是为什么呢?希望有高手指点一下。
里面没什么新的技术,只是最近需要把办事处的文件做同步更新,所以开放了文件下载功能,办事处的客户端自动下载服务器最新文件。借此机会把自己的一点经历记录一下,也希望有人来交流一下。