Monday, October 28, 2013

Uploading/saving image file content to DB with resizing (EF Code First, SQLServer 2008 R2, MVC4)

File uploading is a very common task in nowadays specially with web applications. Normally what we do is we save the uploading files in the server-side. Recently, I have developed a software component which can be used to save images directly to a database table field(even with re-sizing if needed). For this module, I have used Entity Framework, Sql Server 2008 R2 and MVC4. How it has been achieved is described below.

Table - Content


Content table contains two fields FileName, FileContent and FIleType, which are nvarchar(64), varbinary(MAX) and nvarchar(64) respectively. The file contain was stored in FileContent field.

Entity Class - Content

Entity Map - ContentMap

Helper Class - ImageHelper 
I have implemented ToByteArray method as an extension method for HttpPostedFileBase. As this described if the image dimension is not meet your desired height or width it will be resized and stored.

Note: If you are hoping to store non-image files in DB, still it can be accomplished using ToByteArray extension method.
   
View

Controller - ContentFileController
I have used the extension method ToByteArray with the width and height parameters which obtained by web.config.

View - Uploaded Files

Output