從ASP.NET 中的URL 下載或串流檔案
您可能會遇到需要從ASP.NET 中的URL下載或串流檔案的情況ASP.NET 應用程式。然而,當這些檔案駐留在虛擬映射目錄中時,就會出現挑戰,無法使用 Server.MapPath 確定它們的實際位置。
對此的解決方案是使用 HttpWebRequest 類別來檢索檔案並串流傳回給客戶端。這允許您透過 URL 而不是檔案路徑存取檔案。
考慮以下程式碼片段:
try { // Create a WebRequest to retrieve the file HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url); // Get a response for the request HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse(); if (fileReq.ContentLength > 0) fileResp.ContentLength = fileReq.ContentLength; // Get the response stream Stream stream = fileResp.GetResponseStream(); // Prepare the response to the client HttpContext.Current.Response.ContentType = MediaTypeNames.Application.Octet; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); HttpContext.Current.Response.AddHeader("Content-Length", fileResp.ContentLength.ToString()); int length; byte[] buffer = new byte[10000]; // Chunk size for reading the file do { // Check if the client is connected if (HttpContext.Current.Response.IsClientConnected) { // Read data into the buffer length = stream.Read(buffer, 0, buffer.Length); // Write it out to the response's output stream HttpContext.Current.Response.OutputStream.Write(buffer, 0, length); // Flush the data HttpContext.Current.Response.Flush(); // Clear the buffer buffer = new byte[buffer.Length]; } else { // Cancel the download if the client has disconnected length = -1; } } while (length > 0); } catch { // Handle any errors that may occur } finally { if (stream != null) { // Close the input stream stream.Close(); } }
透過實作此方法,您可以從URL 串流檔案並直接在中顯示它們瀏覽器或允許使用者將它們儲存到本機系統。
以上是如何從 ASP.NET 中的 URL 下載或串流檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!