将文件从ftp服务器下载到浏览器

时间:2012-01-19 18:12:10

标签: asp.net vb.net ftpwebrequest

我正在创建一个ASP.NET(VB.NET)应用程序,它必须检索已知的远程文件并通过浏览器将其返回给访问者。我试图使用位于此处的Microsoft示例:http://support.microsoft.com/?kbid=812406并遇到错误'此流不支持搜索操作'。我不知道该怎么办。

以下是标有错误行的代码。

Dim ftpWebReq As Net.FtpWebRequest = CType(Net.WebRequest.Create(path), Net.FtpWebRequest)
ftpWebReq.Method = Net.WebRequestMethods.Ftp.DownloadFile
ftpWebReq.KeepAlive = False
ftpWebReq.UsePassive = False
ftpWebReq.Credentials = New Net.NetworkCredential(System.Web.Configuration.WebConfigurationManager.AppSettings("FtpId"), System.Web.Configuration.WebConfigurationManager.AppSettings("FtpPwd"))
Dim ftpWebResp As Net.FtpWebResponse = CType(ftpWebReq.GetResponse(), Net.FtpWebResponse)
Dim streamer As Stream = ftpWebResp.GetResponseStream()

Dim buffer(10000) As Byte   ' Buffer to read 10K bytes in chunk:
Dim length As Integer       ' Length of the file:
Dim dataToRead As Long      ' Total bytes to read:
dataToRead = streamer.Length    ' *** This is the error line ***
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; filename=foo.txt")
While dataToRead > 0    ' Read the bytes.
If Response.IsClientConnected Then    ' Verify that the client is connected.
   length = streamer.Read(buffer, 0, 10000) ' Read the data in buffer
   Response.OutputStream.Write(buffer, 0, length)  ' Write the data to the current output stream.
   Response.Flush()        ' Flush the data to the HTML output.
   ReDim buffer(10000) ' Clear the buffer
   dataToRead = dataToRead - length
Else
   dataToRead = -1 'prevent infinite loop if user disconnects
End If
End While

1 个答案:

答案 0 :(得分:0)

不要打扰dataToRead。继续阅读,直到length为0(即streamer.Read()已返回0)。这意味着您已到达流的末尾。

我的VB有点生疏,但我认为循环应该是这样的:

finished = False
While Not finished    ' Read the bytes.
    If Response.IsClientConnected Then    ' Verify that the client is connected.
        length = streamer.Read(buffer, 0, 10000) ' Read the data in buffer
        If length > 0 Then
            Response.OutputStream.Write(buffer, 0, length)  ' Write the data to the current output stream.
            Response.Flush()        ' Flush the data to the HTML output.
            ReDim buffer(10000) ' Clear the buffer
        Else
            finished = True
        End If
    Else
        finished = True
    End If
End While