[英]Store file in SQL Server database using .Net MVC3 with Entity Framework
I want to store and retrieve a file into/from SQL Server. 我想在SQL Server中存储文件或从中检索文件。
My infrastructure is: 我的基础架构是:
Please help me out with datatypes that I have to use on SQL Server and C# file. 请帮我解决我必须在SQL Server和C#文件上使用的数据类型。 If possible to store file without refreshing the page that would be more closer to my requirement. 如果可以在不刷新页面的情况下存储文件,那将更符合我的要求。
Thanks. 谢谢。
Here's some "sample codes" ;) I omitted bunch of declarations, validation, etc. so the code will not run as is, but you should be able to get the idea. 这是一些“示例代码”;)我省略了一些声明,验证等,因此该代码不会按原样运行,但是您应该能够理解。 Use ajax type request to submit your file form if you don't want to refresh the page. 如果您不想刷新页面,请使用ajax类型请求提交文件表单。
// model
public class UploadedImage
{
public int UploadedImageID { get; set; }
public string ContentType { get; set; }
public byte[] File { get; set; }
}
// controller
public ActionResult Create()
{
HttpPostedFileBase file = Request.Files["ImageFile"];
if (file.ContentLength != 0)
{
UploadedImage img = new UploadedImage();
img.ContentType = file.ContentType;
img.File = new byte[file.ContentLength];
file.InputStream.Read(img.File, 0, file.ContentLength);
db.UploadedImages.Add(img);
db.SaveChanges();
}
return View();
}
ActionResult Show(int id)
{
var image = db.UploadedImages.Find(id);
if (image != null)
{
return File(image.File, image.ContentType, "filename goes here");
}
}
Sql Datatype is image SQL数据类型是图像
Here is a great article that tells how to do this. 这是一篇很棒的文章,告诉您如何执行此操作。
http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx
Good luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.