![](/img/trans.png)
[英]download blob file from sql using c# asp.net and do not displaying in their related viewer applications?
[英]download blob file from sql using c# asp.net and present a save dialog to user
我已經在網上搜索了兩個小時。 盡管將blob文件上傳到sql數據庫似乎很容易,但是嘗試再次下載它是一場噩夢。
我有一個顯示記錄的gridview。 網格視圖具有一個鏈接按鈕,我想使用該按鈕下載blob文件,但該文件保存在與gridview從中加載其數據的位置相同的表中。 我通過onclick事件將記錄id傳遞給我的代碼隱藏函數。
這是我的on click事件的代碼
protected void Downloadbutton_Click(Object sender, CommandEventArgs e)
{
string reqid = e.CommandArgument.ToString();
using (SqlConnection connection = new SqlConnection("ConnectionString"))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select Attached_File_Name from ABSENCE_REQUEST where Request_ID = @Request_ID";
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@Request_ID", Convert.ToInt32(20057));
byte[] buffer = (byte[]) cmd.ExecuteScalar();
using (FileStream fs = new FileStream(@"C:\test.pdf", FileMode.Create))
{
fs.Write(buffer, 0, buffer.Length);
}
}
}
我知道在我的代碼中實際上設置了文件的下載位置。 但是,如何更改它,以便系統詢問用戶將文件保存在哪里?
我認為您可以簡單地將數據寫入Response(未經測試),例如:
private void WriteFile (Byte[] bytes, string fileName)
{
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
您可能還想考慮為此創建一個通用處理程序,因此您的代碼將非常相似,但是您可以具有指向文件的鏈接,而不僅僅是單擊按鈕時可用,例如,您的鏈接可能是:
YourWebsite/Downloads/RequestFileHandler.ashx?RequestID=5
下載request_ID為5的文件
編輯
抱歉,完全假設這是用於網頁,但是現在已經意識到可能不是,在這種情況下,您可以使用類似以下內容的方法:
private bool SaveBytesToFile(byte[] butes)
{
var saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() != DialogResult.Cancel)
{
using (var fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
{
fileStream.Write(bytes, 0, bytes.Length);
}
return true;
}
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.