【问题标题】:Download/Stream file from URL - asp.net从 URL 下载/流式传输文件 - asp.net
【发布时间】:2011-04-08 14:41:03
【问题描述】:

我需要流式传输一个文件,这将导致在浏览器中另存为提示。 问题是,文件所在的目录是虚拟映射的,所以我无法使用 Server.MapPath 来确定它的实际位置。该目录与网站不在同一位置(甚至是 Live Box 上的物理服务器)。

我想要类似以下的内容,但这将允许我传递 Web URL,而不是服务器文件路径。

我可能不得不最终从配置基本路径构建我的文件路径,然后附加到路径的其余部分,但希望我可以这样做。

var filePath = Server.MapPath(DOCUMENT_PATH);

if (!File.Exists(filePath))
    return;

var fileInfo = new System.IO.FileInfo(filePath);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(filePath);
Response.End();

【问题讨论】:

  • 您能否详细说明“虚拟映射”的含义?可以通过 URL 访问的虚拟 IIS 文件夹?
  • 它使用VPP路径,这是EpiServer CMS使用的概念我们设置虚拟路径名称(即“/documents/”),然后指定它也应该映射的物理路径(即“ //服务器名称/文档")。然后系统在运行时创建对目录的引用。您可以毫无问题地通过 Web URL 浏览文件
  • 文件名确实可以通过 URL 访问。我需要使用此 URL 来流式传输文件,而不是服务器路径,因为我无法从 URL 中确定它(使用 MapPath)
  • 如果您知道 URL 并且文件扩展名会在浏览器中打开另存为提示(或者这是您的问题之一?),也许您可​​以将请求重定向到您要下载的文件?否则,user97970 的建议似乎是要走的路。

标签: c# asp.net file-io streaming


【解决方案1】:

您可以使用 HttpWebRequest 获取文件并将其流式传输回客户端。这使您可以使用 url 获取文件。我发现的一个例子(但不记得在哪里给予信任)是

    //Create a stream for the file
    Stream stream = null;

    //This controls how many bytes to read at a time and send to the client
    int bytesToRead = 10000;

    // Buffer to read bytes in chunk size specified above
    byte[] buffer = new Byte[bytesToRead];

    // The number of bytes read
    try
    {
      //Create a WebRequest to get the file
      HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);

      //Create a response for this request
      HttpWebResponse fileResp = (HttpWebResponse) fileReq.GetResponse();

      if (fileReq.ContentLength > 0)
        fileResp.ContentLength = fileReq.ContentLength;

        //Get the Stream returned from the response
        stream = fileResp.GetResponseStream();

        // prepare the response to the client. resp is the client Response
        var resp = HttpContext.Current.Response;

        //Indicate the type of data being sent
        resp.ContentType = MediaTypeNames.Application.Octet;
    
        //Name the file 
        resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
    
        int length;
        do
        {
            // Verify that the client is connected.
            if (resp.IsClientConnected)
            {
                // Read data into the buffer.
                length = stream.Read(buffer, 0, bytesToRead);

                // and write it out to the response's output stream
                resp.OutputStream.Write(buffer, 0, length);

                // Flush the data
                resp.Flush();

                //Clear the buffer
                buffer = new Byte[bytesToRead];
            }
            else
            {
                // cancel the download if client has disconnected
                length = -1;
            }
        } while (length > 0); //Repeat until no data is read
    }
    finally
    {
        if (stream != null)
        {
            //Close the input stream
            stream.Close();
        }
    }

【讨论】:

  • 每次运行都刷新响应并重新创建缓冲区是不必要的——它只会减慢传输速度。另外,我认为您应该重命名一些变量(fileReq -> urlRequest,fileResp -> urlResponse)。也没有理由创建 Stream 变量,一开始,您应该在使用它的地方创建它(靠近 GetResponseStream() 调用)
  • @data_smith 你为什么不试试你的建议?它不会编译。缓冲区的目的是降低 Web 服务器上的内存使用率。
  • resp 在此示例中未定义:代码无法编译。
  • 正如@Sharon 提到的,此代码无法编译。你需要做的是,在// prepare the response to the client. resp is the client Response 的评论中,添加这段代码:var resp = HttpContext.Current.Response;
  • 我知道我玩游戏很晚了,但非常感谢你分享这个 :) 我正在寻找一种从远程位置/URL 流式传输文件的解决方案,这非常适合我。我所做的唯一更改是我将HttpWebRequest 替换为SafeWebRequest
【解决方案2】:

将url下载为字节并将字节转换为流:

using (var client = new WebClient())
{
    var content = client.DownloadData(url);
    using (var stream = new MemoryStream(content))
    {
        ...
    }
}   

【讨论】:

  • 虽然这看起来很简单并且工作正常,但您需要记住,此解决方案会将文件加载到您的计算机内存中。因此,当 1)数据太大或 2)同时发出多个请求时,由于内存不足而导致异常的可能性很高。
  • Benjamin,这个问题可以通过使用 HttpClient 来缓解。
【解决方案3】:

我经常这样做,并认为我可以添加一个更简单的答案。我在这里将它设置为一个简单的课程,但我每天晚上都运行它来收集我关注的公司的财务数据。

class WebPage
{
    public static string Get(string uri)
    {
        string results = "N/A";

        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            StreamReader sr = new StreamReader(resp.GetResponseStream());
            results = sr.ReadToEnd();
            sr.Close();
        }
        catch (Exception ex)
        {
            results = ex.Message;
        }
        return results;
    }
}

在这种情况下,我传入一个 url,它以 HTML 形式返回页面。如果你想对流做一些不同的事情,你可以很容易地改变它。

你可以这样使用它:

string page = WebPage.Get("http://finance.yahoo.com/q?s=yhoo");

【讨论】:

  • 我的情况不同,有一个文档管理系统并以 .tif 格式返回文档,其中 no 在查询字符串中发送。示例:link 但此方法不起作用,任何想法都值得赞赏。谢谢
  • @kayhanyüksel:我尝试了那个链接,但它超时了。对不起。
【解决方案4】:

2 年后,我使用了达拉斯的答案,但我不得不将 HttpWebRequest 更改为 FileWebRequest,因为我正在链接到直接文件。不确定是否到处都是这种情况,但我想我会添加它。另外,我删除了

var resp = Http.Current.Resonse

并且在任何引用 resp 的地方都使用了 Http.Current.Response。

【讨论】:

  • 完美。我稍微剥夺了达拉的答案。我在下面发布我的版本
【解决方案5】:

如果您正在寻找 @Dallas 答案的 .NET Core 版本,请使用以下内容。

        Stream stream = null;

        //This controls how many bytes to read at a time and send to the client
        int bytesToRead = 10000;

        // Buffer to read bytes in chunk size specified above
        byte[] buffer = new Byte[bytesToRead];

        // The number of bytes read
        try
        {
            //Create a WebRequest to get the file
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(@"file url");

            //Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

            if (fileReq.ContentLength > 0)
                fileResp.ContentLength = fileReq.ContentLength;

            //Get the Stream returned from the response
            stream = fileResp.GetResponseStream();

            // prepare the response to the client. resp is the client Response
            var resp = HttpContext.Response;

            //Indicate the type of data being sent
            resp.ContentType = "application/octet-stream";

            //Name the file 
            resp.Headers.Add("Content-Disposition", "attachment; filename=test.zip");
            resp.Headers.Add("Content-Length", fileResp.ContentLength.ToString());

            int length;
            do
            {
                // Verify that the client is connected.
                if (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    // Read data into the buffer.
                    length = stream.Read(buffer, 0, bytesToRead);

                    // and write it out to the response's output stream
                    resp.Body.Write(buffer, 0, length);


                    //Clear the buffer
                    buffer = new Byte[bytesToRead];
                }
                else
                {
                    // cancel the download if client has disconnected
                    length = -1;
                }
            } while (length > 0); //Repeat until no data is read
        }
        finally
        {
            if (stream != null)
            {
                //Close the input stream
                stream.Close();
            }
        }

【讨论】:

    【解决方案6】:

    您可以尝试使用带有 IIS 路径前缀的 DirectoryEntry 类:

    using(DirectoryEntry de = new DirectoryEntry("IIS://Localhost/w3svc/1/root" + DOCUMENT_PATH))
    {
        filePath = de.Properties["Path"].Value;
    }
    
    if (!File.Exists(filePath))
            return;
    
    var fileInfo = new System.IO.FileInfo(filePath);
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
    Response.WriteFile(filePath);
    Response.End();
    

    【讨论】:

      【解决方案7】:

      如果我们在 Citrix Netscaler 上使用负载均衡器(没有 WAF 策略),达拉斯接受的解决方案对我们有用。

      当文件与 WAF 关联时,无法通过 Netscaler 的 LB 下载文件,因为当前场景(内容长度不正确)违反了 RFC 并且 AppFW 重置了连接,这不会未关联 WAF 策略时发生。

      所以缺少的是:

      Response.End();

      另请参阅: Trying to stream a PDF file with asp.net is producing a "damaged file"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-19
        • 2018-07-11
        • 1970-01-01
        相关资源
        最近更新 更多