问题:
如何从 ASP.NET 中流式传输文件URL并提示保存在浏览器?
背景:
在这种情况下,文件存储在虚拟映射目录中,使其无法通过 Server.MapPath 访问。目标是在传递 Web URL 而不是服务器文件路径时流式传输文件。
解决方案:
要解决此问题,可以利用 HttpWebRequest 来检索从 URL 获取文件并将其流式传输回客户端。
// Create stream for the file Stream stream = null; // Chunk size for reading bytes int bytesToRead = 10000; // Buffer for reading bytes byte[] buffer = new Byte[bytesToRead]; try { // HTTP request to get the file HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url); // HTTP response for the request HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse(); // Get response stream stream = fileResp.GetResponseStream(); // Client response object var resp = HttpContext.Current.Response; // Indicate data type resp.ContentType = "application/octet-stream"; // File name resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // File size resp.AddHeader("Content-Length", fileResp.ContentLength.ToString()); int length; do { // Client connected? if (resp.IsClientConnected) { // Read data into buffer length = stream.Read(buffer, 0, bytesToRead); // Write data to output stream resp.OutputStream.Write(buffer, 0, length); // Flush data resp.Flush(); // Clear buffer buffer = new Byte[bytesToRead]; } else { // Cancel if client disconnected length = -1; } } while (length > 0); } finally { // Close input stream if (stream != null) stream.Close(); }
以上是如何在 ASP.NET 中从 URL 流式传输并提示下载文件?的详细内容。更多信息请关注PHP中文网其他相关文章!