[英]Entity framework 4 and sql filestream to read a file from db
我在SQL 2008中使用ASP.NET 4,EF 4和FILESTREAM向數據庫添加/讀取文件。 我可以上載文件,但無法以我想要的方式檢索文件。 這是我在做什么-
我可以將流寫入臨時文件(使用System.IO.File.WriteAllBytes),然后將Server.Transfer傳輸到臨時文件,但我認為這是不必要的步驟。 有沒有辦法,我可以直接將字節讀取到內存中,然后設置ContentType / MimeType並允許用戶保存文件?
我知道使用T-SQL訪問FILESTREAM文件要比使用WIN32 API(使用新的SystemFile.PathName()和Impersonation的組合)訪問文件更慢,但是EF4使使用SQL的速度更快,所以我走了這條路。
這是代碼-
var file = db.Storage.Single(f => f.ID.Equals(fileID)); // fileID is set in CommandArgument
// file.Contents has the byte [].
// display a standard file download box.
謝謝你的幫助!
您可能要創建一個.ashx處理程序(假設您正在使用asp),並創建到該URL的Server.Transfer()或Server.Redirect()。
或者,您可以更改GridView以顯示指向處理程序URL的超鏈接。
右鍵單擊解決方案資源管理器>新建項目> ASP.Net Hanlder。
處理程序代碼:
public class DownloadFile : IHttpHandler { // add IRequiresSessionState if needed
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context) {
var fileID = context.Request.QueryString["fileID"]; // assuming fileID is a string
var file = db.Storage.Single(f => f.ID.Equals(fileID));
// set the content type
context.Response.OutputStream.Write(file.Contents, 0, file.Contents.Length);
}
}
您可能還想添加一些錯誤檢查。
您的URL可能是這樣的: /DownloadFile.ashx?fileID=somefileid
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.