Tuesday 19 November 2013

How to Save a File to SQL Database

Here are the steps on how to save a file to sql database using LINQ.


  1. Define your table. In this sample we created an Attachments table having 3 fields FileID (int), FileName (nvarchar(100)) and FileContent (varbinary(MAX)). FileContent field will contain the bytes of our file. We set it to MAX to accommodate any file size.










  1. Add your table to your repository module. In this case I used a simple LINQ to SQL just to make it simple















I created a simple repository class to expose some methods like add, save and get.

public class AttachmentRepository
{
    private DataClassesDataContext db = new DataClassesDataContext();

       public AttachmentRepository()
       {
              //
              // TODO: Add constructor logic here
              //
       }

    public void Add(Attachment at)
    {
        db.Attachments.InsertOnSubmit(at);
    }

    public void Save()
    {
        db.SubmitChanges();
    }

    public List<Attachment> GetAllAttachments()
    {
        return db.Attachments.ToList();
    }
}


  1. Layout your UI. Here we have two controls asp FileUploader and asp Button.






  1. Add a button click event on your upload button. In the code below, we only add a file to the database if there is a file uploaded using .HasFile property. Since we already have a repository using LINQ to SQL we can directly assign the Filename and FileBytes to our attachment class.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUploadSample.HasFile)
        {
            AttachmentRepository atRepo = new AttachmentRepository();
            Attachment at = new Attachment();
            at.FileName = FileUploadSample.FileName;
            at.FileContent = FileUploadSample.FileBytes;
            atRepo.Add(at);
            atRepo.Save();
        }       
   }


  1. Verify your Database if the file was indeed saved.








Finally I added a gridview to show the uploaded data









No comments:

Post a Comment