Reputation: 113
I have a link like this: C:\folder\folder\image.jpg . How can I save image to database in SQL Server?
If it was a HttpPostedFileBase I would knew how to save it, but now I have only a link.
Thank you.
Upvotes: 0
Views: 2160
Reputation: 7385
Example from msdn social:
table:
CREATE TABLE [dbo].[FileStoreDemo](
[id] [int] NOT NULL,
[name] [nvarchar](100) NOT NULL,
[content] [varbinary](max) NULL,
CONSTRAINT [pk_filestoredemo_id] PRIMARY KEY CLUSTERED ([id] ASC))
code:
string filename = Server.MapPath("/Content/Desert.jpg")
using (fooEntities fe = new fooEntities())
{
FileStoreDemo fsd = fe.FileStoreDemoes.CreateObject();
fsd.name = new FileInfo(filename).Name;
fsd.content = File.ReadAllBytes(filename);
fe.FileStoreDemoes.AddObject(fsd);
fe.SaveChanges();
}
http://social.msdn.microsoft.com/Forums/en/sqlgetstarted/thread/1857938d-b74a-4954-bbde-734dfef08039
Upvotes: 0
Reputation: 538
[HttpPost]
public ActionResult Create(string fileTitle)
{
try
{
HttpPostedFileBase file = Request.Files[0];
byte[] imageSize = new byte[file.ContentLength];
file.InputStream.Read(imageSize, 0, (int)file.ContentLength);
Image image = new Image()
{
Name = file.FileName.Split('\\').Last(),
Size = file.ContentLength,
Title = fileTitle,
ID = 1,
Image1 = imageSize
};
db.Images.AddObject(image);
db.SaveChanges();
return RedirectToAction("Detail");
}
catch(Exception e)
{
ModelState.AddModelError("uploadError", e);
}
return View();
}
Upvotes: 0
Reputation: 294417
Have a look at Download and Upload Images from SQL Server via ASP.Net MVC
Code is also available on codeproject.com
Upvotes: 1