栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您可以使用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 = "application/octet-stream";        //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();        }    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421475.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号