简体   繁体   中英

Store file in SQL Server database using .Net MVC3 with Entity Framework

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

My infrastructure is:

  • SQL Server 2008
  • C# .Net MVC3 with Entity Framework.

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.

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.

// 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

Here is a great article that tells how to do this.

http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM