从 URL 下载/流文件 - asp.net [英] Download/Stream file from URL - asp.net

查看:23
本文介绍了从 URL 下载/流文件 - asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to stream a file which will result in save as prompt in the browser. The issue is, the directory that the file is located is virtually mapped, so I am unable to use Server.MapPath to determine it's actual location. The directory is not in the same location (or even phyical server on the live boxes) as the website.

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

I'd like something like the following, but that will allow me to pass a web URL, and not a server file path.

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

I may have to end up building my file path from a config base path, and then append on the rest of the path, but hopefully I can do it this way instead.

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();

推荐答案

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

You could use HttpWebRequest to get the file and stream it back to the client. This allows you to get the file with a url. An example of this that I found ( but can't remember where to give credit ) is

    //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 下载/流文件 - asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆