-->

How to upload multiple file with related parameter like file name, size etc. to SQL Server database using ASP.NET

Introduction

In this post, I explain how to upload multiple files with a related parameter to MSSQL Server database using asp.net c#?
In this tutorial, I explain how to upload multiple files with a related parameter like file name, size, content type etc, to SQL database. For this tutorial I will make an file upload system, where we can upload multiple files(e.g. images, PDF's, Doc's or any file types), Show uploaded files and download file.

Steps :

Step - 1: Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table for Store File(s) data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one table as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Webpage and Design for upload and download files(multiple) to/from a database.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML and Java Script Code
Write this javascript code for add dynamic file uploader control.

  1. <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
  2. <script language="javascript" type="text/javascript">
  3. $(function () {
  4. var scntDiv = $('#FileUploaders');
  5. var i = $('#FileUploaders p').size() + 1;
  6.  
  7. $('#addUploader').live('click', function () {
  8. $('<p><input type="file" id="FileUploader' + i + '" name="FileUploader' + i + '" /></label> <a href="#" id="removeUploader">Remove</a></p>').appendTo(scntDiv);
  9. i++;
  10. return false;
  11. });
  12.  
  13. $('#removeUploader').live('click', function () {
  14. if (i > 2)
  15. {
  16. $(this).parents('p').remove();
  17. i--;
  18. }
  19. return false;
  20. });
  21. });
  22.  
  23. </script>
  1.  
  2. <h3>Upload multiple files to SQL Server Database using ASP.NET C#.</h3>
  3. <div style="padding:10px; border:1px solid black">
  4. <div id="FileUploaders">
  5. <p>
  6. <input type="file" id="FileUploader1" name="FileUploader1" />
  7. </p>
  8. </div>
  9. <a href="#" id="addUploader" style="font-size:12pt; color:blue; text-decoration:underline">Add Another</a>
  10. <br />
  11. <asp:Button ID="btnUploadAll" runat="server" Text="Upload File(s)" OnClick="btnUploadAll_Click" />
  12. </div>
  13. <br />
  14. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="10" OnRowCommand="GridView1_RowCommand">
  15. <Columns>
  16. <asp:BoundField HeaderText="File name" DataField="FileName" />
  17. <asp:BoundField HeaderText="File Size" DataField="FileSize" />
  18. <asp:TemplateField>
  19. <ItemTemplate>
  20. <asp:LinkButton ID="lbtnDownload" runat="server" CommandName="Download" CommandArgument='<%#Eval("FileID") %>'>
  21. Download</asp:LinkButton>
  22. </ItemTemplate>
  23. </asp:TemplateField>
  24. </Columns>
  25. </asp:GridView>

Step-6: Write code into page load event for show data.

Write below code into Page_Load event for show data from a database.

  1.  
  2. protected void Page_Load(object sender, EventArgs e)
  3. {
  4. this.Form.Enctype = "multipart/form-data"; // this is required to enable multi file upload
  5. if (!IsPostBack)
  6. {
  7. PopulateUploadedFiles();
  8. }
  9. }
N.B.: Make sure to make add this.Form.Enctype = "multipart/form-data"; to enable multi files upload possible.
   And here is the functioin PopulateUploadedFiles

  1.  
  2. private void PopulateUploadedFiles()
  3. {
  4. // Populate data
  5. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  6. {
  7. GridView1.DataSource = dc.UploadedFiles.ToList();
  8. GridView1.DataBind();
  9. }
  10. }

Step-7: Write code for Upload multiple file(s) to database.

Write below code into button click event for Upload file(s) to database.

  1. protected void btnUploadAll_Click(object sender, EventArgs e)
  2. {
  3. HttpFileCollection filesColl = Request.Files;
  4. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  5. {
  6. foreach (string uploader in filesColl)
  7. {
  8. HttpPostedFile file = filesColl[uploader];
  9.  
  10. if (file.ContentLength > 0)
  11. {
  12. BinaryReader br = new BinaryReader(file.InputStream);
  13.  
  14. byte[] buffer = br.ReadBytes(file.ContentLength);
  15.  
  16. dc.UploadedFiles.Add(new UploadedFile
  17. {
  18. FileID = 0,
  19. FileName = file.FileName,
  20. ContentType = file.ContentType,
  21. FileExtention = Path.GetExtension(file.FileName),
  22. FileSize = file.ContentLength,
  23. FileContent = buffer
  24. });
  25. }
  26. }
  27. dc.SaveChanges();
  28. }
  29. PopulateUploadedFiles(); // for refress grid data
  30. }

Step-8: Write code for Download file from database.

Write below code into GridView1_RowCommand event for Download file from database.

  1. protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
  2. {
  3. // Add code for download files
  4. if (e.CommandName == "Download")
  5. {
  6. int fileID = Convert.ToInt32(e.CommandArgument.ToString());
  7. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  8. {
  9. var v = dc.UploadedFiles.Where(a => a.FileID.Equals(fileID)).FirstOrDefault();
  10. if (v != null)
  11. {
  12. Response.ContentType = v.ContentType;
  13. Response.AddHeader("content-disposition", "attachment; filename="+v.FileName);
  14. Response.BinaryWrite(v.FileContent);
  15. Response.Flush();
  16. Response.End();
  17. }
  18. }
  19. }
  20. }

Step-9: Run Application.

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.

Related Posts: