Monday, July 22, 2013

Saving File To Database

Database Table: 

CREATE TABLE [dbo].[Documents](

[DocumentId] [int] IDENTITY(1,1) NOT NULL CONSTRAINT [PK_Documents] PRIMARY KEY,

[DocumentData] [varbinary](max) NOT NULL,

[DocumentName] [varchar](50) NOT NULL,

[DocumentType] [varchar](50) NOT NULL,

 )

In View,
We need a File Upload control for uploading the file.

 @using (Html.BeginForm("Index", "UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            < input id="postedFile" name="postedFile" type="file" />
            < input title="Upload File" type="submit" value="Upload File" />
        }

Here UploadFile is the Controller and Index is the action method. "enctype" is important attribute for uploading documents. 

In Controller,
[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
   int fileSize = postedFile.ContentLength;
   string fileName = Path.GetFileName(postedFile.FileName);

  SqlConnection connection = new SqlConnection();
  connection.ConnectionString =    ConfigurationManager.ConnectionStrings["uploadFileCon"].ConnectionString;

   SqlCommand cmd = new SqlCommand();               
   cmd.CommandText = "INSERT INTO Documents(DocumentName,DocumentType,DocumentData)" +
                                  " VALUES (@DocName,@Type,@DocData)";
    cmd.CommandType = CommandType.Text;
                cmd.Connection = connection;

                SqlParameter DocName = new SqlParameter("@DocName", SqlDbType.VarChar, 50);
                DocName.Value = fileName.ToString();
                cmd.Parameters.Add(DocName);

                SqlParameter Type = new SqlParameter("@Type", SqlDbType.VarChar, 50);
                Type.Value = postedFile.ContentType.ToString();
                cmd.Parameters.Add(Type);

                byte[] documentbinary = new byte[fileSize];
                postedFile.InputStream.Read(documentbinary, 0, fileSize);

                SqlParameter uploadedDocument = new SqlParameter("@DocData", SqlDbType.Binary, fileSize);
                uploadedDocument.Value = documentbinary;
                cmd.Parameters.Add(uploadedDocument);

                connection.Open();
                int result = cmd.ExecuteNonQuery();
                connection.Close();
}