本文實例講述了ASP.NET實現推送文件到浏覽器的方法。分享給大家供大家參考。具體分析如下:
這裡主要實現從服務器到浏覽器,推送文件,提供用戶下載/浏覽的功能。
提示: 在AJAX UpdatePanel裡面將無效。如果代碼從按鈕單擊事件中被調用,該按鈕需要在 AJAX UpdatePanel的外部。
具體代碼如下:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 /// <summary> /// Downloads (pushes) file to the client browser. /// **** NOTE **** Cannot be done from inside an AJAX UpdatePanel control. /// </summary> /// <param name="fullFilePath">The full file path of the file</param> protected void DownloadFile(string fullFilePath) { // Gets the File Name string fileName = fullFilePath.Substring(fullFilePath.LastIndexOf('\') + 1); byte[] buffer; using (FileStream fileStream = new FileStream(fullFilePath, FileMode.Open)) { int fileSize = (int)fileStream.Length; buffer = new byte[fileSize]; // Read file into buffer fileStream.Read(buffer, 0, (int)fileSize); } Response.Clear(); Response.Buffer = true; Response.BufferOutput = true; Response.ContentType = "application/x-download"; Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); Response.CacheControl = "public"; // writes buffer to OutputStream Response.OutputStream.Write(buffer, 0, buffer.Length); Response.End(); }希望本文所述對大家的asp.net程序設計有所幫助。