[英]Entity framework 4 and sql filestream to read a file from db
I'm using ASP.NET 4, EF 4 and FILESTREAM in SQL 2008 to add/read files to the DB. 我在SQL 2008中使用ASP.NET 4,EF 4和FILESTREAM向数据库添加/读取文件。 I'm able to upload files just fine, but I'm not able to retrieve the files the way I want to.
我可以上载文件,但无法以我想要的方式检索文件。 Here's what I'm doing -
这是我在做什么-
I can write the stream to a temp file (using System.IO.File.WriteAllBytes) and then do a Server.Transfer to the temp file but I think it's an unnecessary step. 我可以将流写入临时文件(使用System.IO.File.WriteAllBytes),然后将Server.Transfer传输到临时文件,但我认为这是不必要的步骤。 Is there a way, I can read the bytes directly to memory, then set the ContentType/MimeType and allow the user to save the file?
有没有办法,我可以直接将字节读取到内存中,然后设置ContentType / MimeType并允许用户保存文件?
I understand that accessing the FILESTREAM file using T-SQL is slower than accessing the same using WIN32 API's (using a combination of the new SystemFile.PathName() & Impersonation) but EF4 makes working with SQL faster so I'm going that route. 我知道使用T-SQL访问FILESTREAM文件要比使用WIN32 API(使用新的SystemFile.PathName()和Impersonation的组合)访问文件更慢,但是EF4使使用SQL的速度更快,所以我走了这条路。
Here's the code - 这是代码-
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.
Thanks for any help! 谢谢你的帮助!
You probably want to create an .ashx hanlder (assuming you are using asp) and to a Server.Transfer() or Server.Redirect() to that URL. 您可能要创建一个.ashx处理程序(假设您正在使用asp),并创建到该URL的Server.Transfer()或Server.Redirect()。
Alternatively, you could change the GridView to display a hyperlink to the handler URL as well. 或者,您可以更改GridView以显示指向处理程序URL的超链接。
Right click in Solution Explorer > New Item > ASP.Net Hanlder. 右键单击解决方案资源管理器>新建项目> ASP.Net Hanlder。
Code for handler: 处理程序代码:
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);
}
}
You probably want to add some error checking as well. 您可能还想添加一些错误检查。
Your URL would be something like this: /DownloadFile.ashx?fileID=somefileid
您的URL可能是这样的:
/DownloadFile.ashx?fileID=somefileid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.