從ASP.NET 中的URL 下載和串流檔案
在ASP.NET 中,在瀏覽器中提示儲存提示的串流檔案可以是使用Server.MapPath 實作。但是,當檔案位於虛擬映射目錄中時,此方法可能無法運作。以下是使用 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 = MediaTypeNames.Application.Octet; //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(); } }
此程式碼可讓您指定檔案的 URL,該 URL 可以位於任何位置,無論網站的實體位置為何。它設定適當的標頭並將文件分塊串流傳輸到客戶端,提供無縫的下載體驗。
以上是如何從 ASP.NET 中的 URL 串流檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!