2009-12-14 27 views

回答

7

Here's a Microsoft Knowledge Base article on this.

如何從數據庫中檢索文件取決於您使用的數據訪問技術;我只假設你有一些字節數組data包含文件(例如通過填充數據集並訪問字段)和一些字符串filename

Response.Clear() 
Response.ContentType = "application/octet-stream" 
Response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & """") 
Response.BinaryWrite(data) 
Response.End() 

把上面的代碼放在一些download.aspx並鏈接到這個文件。您可能希望將一些查詢字符串信息傳遞給您的download.aspx,以便您的代碼知道從數據庫中獲取哪個文件。

3

將數據讀入一個文件流對象,並附加適當的擴展名,並讓用戶下載結果文件。

你要使用System.IO的BinaryWriter對象上的FILESTREAM創建文件......像這樣:

FileStream fs = new FileStream("thisfile.bin", FileMode.Create); 
binWriter= new BinaryWriter(fs);  

binWriter.Write(varHoldingSqlRetrievedBinaryData); 
+0

那麼我怎樣才能從二進制數據擴展? – Tarik 2009-12-14 18:00:27

+0

你可以提供一個示例代碼,因爲我知道你在說什麼,但是在代碼方面,我可能需要一個例子:( – Tarik 2009-12-14 18:02:39

+0

有沒有辦法這樣做,最好的方法是將擴展名存儲在數據庫中) – 2009-12-14 18:05:18

2

向您的網站添加一個通用處理程序(.ashx)頁面。下面的ASHX代碼體演示瞭如何讀取(在這種情況下,從磁盤PNG文件)的任意流並寫入在響應:如證明

using System; 
using System.Web; 
using System.IO; 

namespace ASHXTest 
{ 
    public class GetLetter : IHttpHandler 
    { 
     public void ProcessRequest(HttpContext context) 
     { 
      // Get letter parameter from query string. 
      string fileName = context.Request.MapPath(string.Format("{0}.png", 
       context.Request.QueryString["letter"])); 

      // Load file from disk/database/ether. 
      FileStream stream = new FileStream(fileName, FileMode.Open, 
       FileAccess.Read); 
      byte[] buffer = new byte[stream.Length]; 
      stream.Read(buffer, 0, buffer.Length); 
      stream.Close(); 

      // Write response headers and content. 
      context.Response.ContentType = "image/png"; 
      context.Response.OutputStream.Write(buffer, 0, buffer.Length); 
     } 

     public bool IsReusable 
     { 
      get 
      { 
       return false; 
      } 
     } 
    } 
} 

如果需要,還可以設置Content-Disposition頭Heinzi的回答:

context.Response.AddHeader("Content-Disposition", 
    "attachment;filename=\"letter.png\""); 
相關問題