Reputation: 87
I want to store and retrieve a file into/from SQL Server.
My infrastructure is:
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.
Upvotes: 0
Views: 6190
Reputation: 4089
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");
}
}
Upvotes: 4
Reputation: 593
Sql Datatype is image
Here is a great article that tells how to do this.
Good luck.
Upvotes: 0