1

我需要将文件下载为当前 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);
             }
         }
     }
}

但是这个代码请求只是发送但没有得到任何响应......

这可能吗?

4

2 回答 2

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;
    }
}
于 2012-10-11T16:30:30.820 回答
0

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

MSDN 参考

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

于 2012-10-11T16:01:32.537 回答