首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从URL - asp.net下载/流文件

从URL - asp.net下载/流文件
EN

Stack Overflow用户
提问于 2011-04-08 22:41:03
回答 7查看 314.7K关注 0票数 77

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

我希望如下所示,但这将允许我传递web URL,而不是服务器文件路径。

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

代码语言:javascript
复制
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();
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2011-04-09 22:02:38

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

代码语言:javascript
复制
    //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();
        }
    }
票数 111
EN

Stack Overflow用户

发布于 2016-02-11 01:49:47

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

代码语言:javascript
复制
using (var client = new WebClient())
{
    var content = client.DownloadData(url);
    using (var stream = new MemoryStream(content))
    {
        ...
    }
}   
票数 30
EN

Stack Overflow用户

发布于 2015-06-02 22:37:59

我这样做了很多,我想我可以添加一个更简单的答案。我在这里将它设置为一个简单的类,但我每天晚上都会运行它来收集我关注的公司的财务数据。

代码语言:javascript
复制
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的形式返回页面。如果你想对流做一些不同的事情,你可以很容易地改变它。

您可以这样使用它:

代码语言:javascript
复制
string page = WebPage.Get("http://finance.yahoo.com/q?s=yhoo");
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5596747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档