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.