問題:
如何從ASP.NET中串流文件網址並提示保存在瀏覽器?
背景:
在這種情況下,檔案儲存在虛擬映射目錄中,使其無法透過 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中文網其他相關文章!