在某些情況下,可能需要從遠端URL 串流或下載檔案並觸發「另存為”瀏覽器中的提示。但是,當檔案位於虛擬映射目錄中時,使用 Server.MapPath 存取其實際位置可能會很困難。
相反,您可以利用 HttpWebRequest 的強大功能來實現此功能。以下是一個允許您傳遞 Web URL 的範例:
using System.IO; using System.Net; namespace FileDownloader { public static class FileDownloader { public static void DownloadFile(string url, string fileName) { // Create a stream for the file Stream stream = null; // Configure streaming chunk size int bytesToRead = 10000; // Buffer to read bytes in specified chunk size byte[] buffer = new Byte[bytesToRead]; // Initialize response HttpWebResponse fileResp = null; try { // Create a WebRequest to get the file HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url); // Get a response for this request fileResp = (HttpWebResponse)fileReq.GetResponse(); // Get the Stream returned from the response stream = fileResp.GetResponseStream(); // Prepare the response to the client HttpResponse resp = HttpContext.Current.Response; // Set response type and add headers resp.ContentType = MediaTypeNames.Application.Octet; resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); resp.AddHeader("Content-Length", fileResp.ContentLength.ToString()); int length; do { // Verify client connection if (resp.IsClientConnected) { // Read data into the buffer length = stream.Read(buffer, 0, bytesToRead); // Write data 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 download if client disconnects length = -1; } } while (length > 0); // Repeat until no data remains } finally { // Close the input stream if (stream != null) { stream.Close(); } // Dispose the response if (fileResp != null) { fileResp.Close(); } } } } }
透過使用此方法,您可以從遠端 URL 串流文件,並允許使用者使用動態產生的文件名稱將它們保存在本地。
以上是如何在 ASP.NET 中從遠端 URL 下載和串流檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!