2011-10-28 52 views
1

我在我的SQL數據庫中上傳BLOB文件。我創建動態超鏈接重定向到我的download.aspx.cs,以下載文件。檢索BLOB文件

當我點擊它,我獲取的唯一事情是這樣的事情:

*����JFIF,,��ExifMM*� ���(1�2;%+>P?`���7��i��%��NIKON CORPORATIONNIKON D3-��'-��'Adobe Photoshop CS4 Macintosh2010:11:19 21:53:25 9�I�@d!ddGddd+�K�r� (��Ƃ�Έ"�'@�0221�֐����� ���� � ��,��42��42��42�0100����Р�d����J����R�b���� � ��Z @(2010:11:19 20:44:392010:11:19 20:44:39 � ASCII R030100��(�HH����JFIFHH��Adobe_CM��Adobed����* 

這是本downloading.aspx我的Page_Load代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
    string filename = Request["file"].ToString(); 
    var conString = ConfigurationManager.ConnectionStrings["LocalSqlServer"]; 
    string strConnString = conString.ConnectionString; 
    SqlConnection dbConnection = new SqlConnection(strConnString); 
    dynamic queryString = ("SELECT Data FROM Files WHERE Name = '" + filename + "'"); 
    SqlCommand theCommand = new SqlCommand(queryString, dbConnection); 
    dbConnection.Open(); 
    SqlDataReader reader = theCommand.ExecuteReader(); 

    if (reader.Read() && reader != null) 
    { 
     Byte[] bytes; 
     bytes = Encoding.UTF8.GetBytes(String.Empty); 
     bytes = (Byte[])reader["Data"]; 
     Response.BinaryWrite(bytes); 

     reader.Close(); 
    } 

    dbConnection.Close(); 
} 

有人能告訴我爲什麼?謝謝。

回答

5

您需要設置內容類型和內容部署到您的響應頭添加爲這樣:

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
Response.AddHeader("content-disposition", "attachment; filename=whatever.xlsx"); 
Response.BinaryWrite(yourbytes); 

注意:內容類型必須是特定的文件你流的類型。如果一個圖像,它必須是像「image/jpg」;等等。如果它是一個圖像,可能要將文件名部分的擴展名設置爲「file.jpg」。 以上代碼只是一個例子

+0

如果我還想下載.cs,visual studio文件,pdf?我應該怎麼做 ? 否則,你的代碼是完美的工作!非常感謝 ! – Kiwimoisi

+0

@Emged您需要知道您要傳輸給用戶的文件類型,並適當設置內容處置和內容類型。我的建議是,您還將文件類型存儲在數據庫中,因此您不必嘗試「檢測」分析字節。 – Icarus

+0

@Emged只需使用適當的MIME類型爲您的文件。 http://www.iana.org/assignments/media-types/image/index.html – jbtule

3

您需要將Content-Type,Content-Length和Content-Disposition標頭髮送到瀏覽器,以便它能夠理解二進制數據。

+0

正如伊卡洛斯所說。謝謝你的回答,它幫助了我! – Kiwimoisi