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.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.
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script language="javascript" type="text/javascript"> $(function () { var scntDiv = $('#FileUploaders'); var i = $('#FileUploaders p').size() + 1; $('#addUploader').live('click', function () { $('<p><input type="file" id="FileUploader' + i + '" name="FileUploader' + i + '" /></label> <a href="#" id="removeUploader">Remove</a></p>').appendTo(scntDiv); i++; return false; }); $('#removeUploader').live('click', function () { if (i > 2) { $(this).parents('p').remove(); i--; } return false; }); }); </script>
<h3>Upload multiple files to SQL Server Database using ASP.NET C#.</h3> <div style="padding:10px; border:1px solid black"> <div id="FileUploaders"> <p> <input type="file" id="FileUploader1" name="FileUploader1" /> </p> </div> <a href="#" id="addUploader" style="font-size:12pt; color:blue; text-decoration:underline">Add Another</a> <br /> <asp:Button ID="btnUploadAll" runat="server" Text="Upload File(s)" OnClick="btnUploadAll_Click" /> </div> <br /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="10" OnRowCommand="GridView1_RowCommand"> <Columns> <asp:BoundField HeaderText="File name" DataField="FileName" /> <asp:BoundField HeaderText="File Size" DataField="FileSize" /> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lbtnDownload" runat="server" CommandName="Download" CommandArgument='<%#Eval("FileID") %>'> Download</asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </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.protected void Page_Load(object sender, EventArgs e) { this.Form.Enctype = "multipart/form-data"; // this is required to enable multi file upload if (!IsPostBack) { PopulateUploadedFiles(); } }N.B.: Make sure to make add this.Form.Enctype = "multipart/form-data"; to enable multi files upload possible.
private void PopulateUploadedFiles() { // Populate data using (MyDatabaseEntities dc = new MyDatabaseEntities()) { GridView1.DataSource = dc.UploadedFiles.ToList(); GridView1.DataBind(); } }
Step-7: Write code for Upload multiple file(s) to database.
Write below code into button click event for Upload file(s) to database.protected void btnUploadAll_Click(object sender, EventArgs e) { HttpFileCollection filesColl = Request.Files; using (MyDatabaseEntities dc = new MyDatabaseEntities()) { foreach (string uploader in filesColl) { HttpPostedFile file = filesColl[uploader]; if (file.ContentLength > 0) { BinaryReader br = new BinaryReader(file.InputStream); byte[] buffer = br.ReadBytes(file.ContentLength); dc.UploadedFiles.Add(new UploadedFile { FileID = 0, FileName = file.FileName, ContentType = file.ContentType, FileExtention = Path.GetExtension(file.FileName), FileSize = file.ContentLength, FileContent = buffer }); } } dc.SaveChanges(); } PopulateUploadedFiles(); // for refress grid data }
Step-8: Write code for Download file from database.
Write below code into GridView1_RowCommand event for Download file from database.protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { // Add code for download files if (e.CommandName == "Download") { int fileID = Convert.ToInt32(e.CommandArgument.ToString()); using (MyDatabaseEntities dc = new MyDatabaseEntities()) { var v = dc.UploadedFiles.Where(a => a.FileID.Equals(fileID)).FirstOrDefault(); if (v != null) { Response.ContentType = v.ContentType; Response.AddHeader("content-disposition", "attachment; filename="+v.FileName); Response.BinaryWrite(v.FileContent); Response.Flush(); Response.End(); } } } }