首页 > 后端开发 > C++ > 如何从 ASP.NET 中的 URL 流式传输文件?

如何从 ASP.NET 中的 URL 流式传输文件?

Linda Hamilton
发布: 2025-01-06 08:19:40
原创
558 人浏览过

How to Stream Files from URLs in ASP.NET?

从 ASP.NET 中的 URL 下载和流式传输文件

在 ASP.NET 中,在浏览器中提示保存提示的流式文件可以是使用 Server.MapPath 实现。但是,当文件位于虚拟映射目录中时,此方法可能不起作用。下面是使用 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();
    }
}
登录后复制

此代码允许您指定文件的 URL,该 URL 可以位于任何位置,无论网站的物理位置如何。它设置适当的标头并将文件分块流式传输到客户端,提供无缝的下载体验。

以上是如何从 ASP.NET 中的 URL 流式传输文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板