vb中下載一個apk文件的代碼:
shuye 2012-05-03 03:30:02 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim filename As String = "PHRMOBILE.apk"
fileDownload(filename, Server.MapPath(filename))
End Sub
Private Sub fileDownload(ByVal fileName As String, ByVal fileUrl As String)
Page.Response.Clear()
Dim success As Boolean
success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000)
If Not success Then
Response.Write("Downloading Error!")
End If
Page.Response.End()
End Sub
Public Function ResponseFile(ByVal _Request As HttpRequest, ByVal _Response As HttpResponse, ByVal _fileName As String, ByVal _fullPath As String, ByVal _speed As Integer) As Boolean
Try
Dim myFile As FileStream = New FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
'Response.Write("<script>alert(' here ')</script>")
Dim br As BinaryReader = New BinaryReader(myFile)
Try
'
_Response.AddHeader("Accept-Ranges", "bytes")
_Response.Buffer = False
Dim fileLength As Long = myFile.Length
Dim startBytes As Long = 0
Dim pack As Integer = 10240
Dim sleep As Integer = CType(Math.Floor(1000 * pack / _speed) + 1, Integer)
If _Request.Headers("Range") <> Nothing Then
_Response.StatusCode = 206
Dim range() As String = _Request.Headers("Range").Split(New Char() {"="c, "-"c})
startBytes = Convert.ToInt64(range(1))
End If
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString())
If startBytes <> 0 Then
_Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength))
End If
_Response.AddHeader("Connection", "Keep-Alive")
_Response.ContentType = "application/octet-stream"
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8))
br.BaseStream.Seek(startBytes, SeekOrigin.Begin)
Dim maxCount As Integer = CType(Math.Floor((fileLength - startBytes) / pack) + 1, Integer)
Dim i As Integer
'For i = 0 To maxCount - 1
For i = 0 To maxCount - 1 Step i + 1
If (_Response.IsClientConnected) Then
_Response.BinaryWrite(br.ReadBytes(pack))
Thread.Sleep(sleep)
Else
i = maxCount
End If
Next
'catch
'{
' return false;
'}
Catch ex As Exception
Return False
Finally
br.Close()
myFile.Close()
End Try
Catch ex As Exception
Return False
End Try
Return True
End Function
End Class