使用。NET MVC3与实体框架在SQL Server数据库中存储文件

问题描述:

我要存储和从SQL Server检索文件到/。

I want to store and retrieve a file into/from SQL Server.

我的基础是:

  • 在SQL Server 2008中
  • 在C#.NET MVC3与实体框架。

请帮助我,我要SQL Server和C#文件上使用的数据类型。如果可能的话来存储文件,而无需刷新页面,这将是更接近我的要求。

Please help me out with datatypes that I have to use on SQL Server and C# file. If possible to store file without refreshing the page that would be more closer to my requirement.

感谢。

下面是一些样品codeS)我省略一堆声明,确认,等于是code将不会运行原样,但你应该能够得到的想法。使用Ajax类型请求提交文件的形式,如果你不想刷新页面。

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.

// 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");
    }
}