文件下载当前请求

时间:2012-10-11 15:32:42

标签: c# .net httpwebrequest

我需要将该文件作为当前http请求的http响应下载。

到目前为止,我使用了代码

System.Uri uri = System.Web.HttpContext.Current.Request.Url;   

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(
    Path.Combine(uri.ToString(), filename));

httpRequest.Method = "GET";

using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{                 
     using (Stream responseStream = httpResponse.GetResponseStream())
     {
         using (FileStream localFileStream = new FileStream(
             Path.Combine(localFolder, filename), FileMode.Open))
         {                  
             int bytesRead;

             while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
             {
                 totalBytesRead += bytesRead;    
                 localFileStream.Write(buffer, 0, bytesRead);
             }
         }
     }
}

但是这段代码请求只发送但没有得到任何回复......

这可能吗?

2 个答案:

答案 0 :(得分:2)

您应该从磁盘上获取文件,然后使用Response.OutputStream将文件直接写入响应。确保设置正确的内容标题,以便浏览器知道将要发生的事情。

FileInfo file = new FileInfo(Path.Combine(localFolder, filename));
int len = (int)file.Length, bytes;
Response.ContentType = "text/plain"; //Set the file type here
Response.AddHeader "Content-Disposition", "attachment;filename=" + filename; 
context.Response.AppendHeader("content-length", len.ToString());
byte[] buffer = new byte[1024];

using(Stream stream = File.OpenRead(path)) {
    while (len > 0 && (bytes =
        stream.Read(buffer, 0, buffer.Length)) > 0)
    {
        Response.OutputStream.Write(buffer, 0, bytes);
        len -= bytes;
    }
}

答案 1 :(得分:0)

不确定,但看起来您正在发出Web请求,获取响应流,然后尝试将其缓冲到localFolder。如果是这样,FileMode.Open看起来很可疑(“应该打开现有文件......”?)。也许使用FileMode.Create。

MSDN ref

此外,您的网络应用程序是否需要具有对localFolder的写入权限。