-->

How to upload and download files to/from a SQL Server database?

Introduction

In this post, I explain how to upload and download files to/from an SQL Server database?
Recently I have completed a project where I need to store various files to the database. Here in this post I explain how to upload and download files to/from an SQL Server database.

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 tables 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 to/from 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 Code

  1. <h3>File Upload / Download from/to Database using ASP.NET</h3>
  2. <div>
  3. <table>
  4. <tr>
  5. <td>Select File : </td>
  6. <td>
  7. <asp:FileUpload ID="FileUpload1" runat="server" /></td>
  8. <td>
  9. <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /></td>
  10. </tr>
  11. </table>
  12. <br />
  13. <div>
  14. <%-- Add a Datalist for show uploaded files --%>
  15. <asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemCommand="DataList1_ItemCommand">
  16. <ItemTemplate>
  17. <table>
  18. <tr>
  19. <td><%#Eval("FileName","File Name : {0}") %></td>
  20. </tr>
  21. <tr>
  22. <td><%#String.Format("{0:0.00}",Convert.ToDecimal(Eval("FileSize"))/1024)%> KB</td>
  23. </tr>
  24. <tr>
  25. <td>
  26. <asp:LinkButton ID="lbtnDownload" runat="server" CommandName="Download" CommandArgument=<%#Eval("FileID") %>>Download</asp:LinkButton></td>
  27. </tr>
  28. </table>
  29. </ItemTemplate>
  30. </asp:DataList>
  31. </div>
  32. </div>

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

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

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. PopulateUploadedFiles();
  6. }
  7. }

   And here is the functioin PopulateUploadedFiles

  1. private void PopulateUploadedFiles()
  2. {
  3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  4. {
  5. List<UploadedFile> allFiles = dc.UploadedFiles.ToList();
  6. DataList1.DataSource = allFiles;
  7. DataList1.DataBind();
  8. }
  9. }

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

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

  1. protected void btnUpload_Click(object sender, EventArgs e)
  2. {
  3. // Code for Upload file to database
  4. if (FileUpload1.HasFile)
  5. {
  6. HttpPostedFile file = FileUpload1.PostedFile;
  7. BinaryReader br = new BinaryReader(file.InputStream);
  8. byte[] buffer = br.ReadBytes(file.ContentLength);
  9.  
  10. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  11. {
  12. dc.UploadedFiles.Add(
  13. new UploadedFile
  14. {
  15. FileName = file.FileName,
  16. ContentType = file.ContentType,
  17. FileID = 0,
  18. FileSize = file.ContentLength,
  19. FileExtension = Path.GetExtension(file.FileName),
  20. FileContent = buffer
  21. });
  22. dc.SaveChanges();
  23. PopulateUploadedFiles();
  24. }
  25. }
  26. }

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

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

  1. protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
  2. {
  3. if (e.CommandName == "Download")
  4. {
  5. int fileID = Convert.ToInt32(e.CommandArgument);
  6. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  7. {
  8. var v = dc.UploadedFiles.Where(a => a.FileID.Equals(fileID)).FirstOrDefault();
  9. if (v != null)
  10. {
  11. byte[] fileData = v.FileContent;
  12. Response.AddHeader("Content-type", v.ContentType);
  13. Response.AddHeader("Content-Disposition", "attachment; filename=" + v.FileName);
  14.  
  15. byte[] dataBlock = new byte[0x1000];
  16. long fileSize;
  17. int bytesRead;
  18. long totalsBytesRead = 0;
  19.  
  20. using (Stream st = new MemoryStream(fileData))
  21. {
  22. fileSize = st.Length;
  23. while (totalsBytesRead < fileSize)
  24. {
  25. if (Response.IsClientConnected)
  26. {
  27. bytesRead = st.Read(dataBlock, 0, dataBlock.Length);
  28. Response.OutputStream.Write(dataBlock, 0, bytesRead);
  29.  
  30. Response.Flush();
  31. totalsBytesRead += bytesRead;
  32. }
  33. }
  34. }
  35. Response.End();
  36. }
  37. }
  38. }
  39. }

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: