Reputation: 3515
I have one test real estate app. with poor performance issues. One property can have one or more images.
Those images are stored as binaries in database, now I want to create I hope better solution with save image inside server hdd and with reference path inside db.
I have no clue how to do this. How should I design my db table? How to save image to server and its path to the db? I'll post my current code.
Worth to mention is that I need solution where I should upload image together with other property information (on the same page, with browse buttons).
Entities
public class Property
{
public Guid Id {get; set;}
public string Name {get; set;}
...
public List<Photo>Photos {get; set;}
}
public class Photo
{
public Property Property {get; set;}
public byte[] ImageData {get; set;}
public string ImageMimeType {get; set;}
}
Db design
Photo table
Id int
ImageData varbinary(MAX)
ImageMimeType varchar(50)
Version int
PropertyId int
Handling posted images and other data inside controller
[HttpPost]
public ActionResult Create(PropertyViewModel newData, IEnumerable<HttpPostedFileBase> images)
{
if (ModelState.IsValid)
{
using (ISession session = ...GetCurrentSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
Domain.Property model = new Domain.Property();
newData.ToDomainModel(model, images);
transaction.Commit();
session.Save(model);
}
}
return RedirectToAction("Index");
}
else
{
return View(newData);
}
}
and finally inside ViewModel.ToDomain I save posted images like this.
Note that IEnumerable Images are posted from webform
List<Photo> Photos = new List<Photo>();
foreach (var image in Images)
{
if (image != null && image.ContentLength > 0)
{
Photo p = new Photo();
p.Property = x;
p.ImageMimeType = image.ContentType;
p.ImageData = new byte[image.ContentLength];
image.InputStream.Read(p.ImageData, 0, image.ContentLength);
Photos.Add(p);
}
}
x.Photos = new List<Photo>();
x.Photos = Photos;
This approach works, mapping between entities is ok, now what should I change in order to save images on server hdd and its reference to db.
Upvotes: 2
Views: 415
Reputation: 24433
Storing data as raw files on the db server disk has its own problems, the main one being that you have to configure access to the file system from your client - in this case the web server.
If you're using Sql Server 2008 or later, there is a middle ground: FILESTREAM
The data is stored in files, but is accessible through the database. So you get referential integrity and access through your database connection, without bloating the database itself.
Upvotes: 1