Upload and Download Files From Database in Web API

Introduction

This article explains how to upload files in the database and download files from the database in the ASP.NET Web API. This file can be a text file or an image file.

The procedure for creating the application is as in the following.

Step 1

First we create a database in SQL.

  • Open SQL Server 2012.
  • Select "New Query" and create the database and table.

The following commands are used for creating the database and table:

  1. create database Demo  
  2. use Demo  
  3. create table Datafile(ID int IDENTITY NOT NULL,Filerecord image NOT NULL ,Filetype varchar(50) NOT NULL,Name varchar(50) NOT NULL) 

Step 2

Create the Web API application:

  • Start Visual Studio 2012.

  • From the start window select "New Project".

  • In the Template window select "Installed" -> "Visual C#" -> "Web".

  • Select "ASP.NET MVC4 Web Application" and click the "OK" button.

    dwn.jpg

  • From the "MVC4 Project" window select "Web API".

    dwn1.jpg

  • Click the "OK" button.

Step 3

Open the "HomeController" file and write the code for uploading the file in the database. This file exists:

  • In the "Solution Explorer".

  • Select "Controller" -> "HomeController".

    dwn3.jpg

Add the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.SqlClient;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8. namespace FileUploadDatabase.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         public bool Infile(HttpPostedFileBase imgfile)  
  13.         {  
  14.             return (imgfile != null && imgfile.ContentLength > 0) ? true : false;  
  15.         }  
  16.         public ActionResult Index()  
  17.         {  
  18.             foreach (string Save in Request.Files)  
  19.             {  
  20.                 if (!Infile(Request.Files[Save])) continue;  
  21.                 string fileType = Request.Files[Save].ContentType;  
  22.                 Stream file_Strm = Request.Files[Save].InputStream;  
  23.                 string file_Name = Path.GetFileName(Request.Files[Save].FileName);  
  24.                 int fileSize = Request.Files[Save].ContentLength;  
  25.                 byte[] fileRcrd = new byte[fileSize];  
  26.                 file_Strm.Read(fileRcrd, 0, fileSize);  
  27.                 const string connect = @"Server=.;Database=Demo; User Id=sa; password=wintellect;";  
  28.                 using (var conn = new SqlConnection(connect))  
  29.                 {  
  30.                     var qry = "INSERT INTO Datafile (Filerecord, Filetype, Name)VALUES (@Filerecord, @Filetype, @Name)";  
  31.                     var cmd = new SqlCommand(qry, conn);  
  32.                     cmd.Parameters.AddWithValue("@Filerecord", fileRcrd);  
  33.                     cmd.Parameters.AddWithValue("@Filetype", fileType);  
  34.                     cmd.Parameters.AddWithValue("@Name", file_Name);  
  35.                     conn.Open();  
  36.                     cmd.ExecuteNonQuery();  
  37.                 }  
  38.             }  
  39.             return View();  
  40.         }  
  41.         public ActionResult DownloadImage()  
  42.         {  
  43.             const string connect = @"Server=.;Database=Demo;User id=sa;password=wintellect;";  
  44.             List<string> fileList = new List<string>();  
  45.             using (var con = new SqlConnection(connect))  
  46.             {  
  47.                 var query = "SELECT Filerecord, Filetype,Name FROM Datafile";  
  48.                 var cmd = new SqlCommand(query, con);  
  49.                 con.Open();  
  50.                 SqlDataReader rdr = cmd.ExecuteReader();  
  51.                 while (rdr.Read())  
  52.                 {  
  53.                     fileList.Add(rdr["Name"].ToString());  
  54.                 }  
  55.             }  
  56.             ViewBag.Images = fileList;  
  57.             return View();  
  58.         }  
  59.         public FileContentResult GetFile(int id)  
  60.         {  
  61.             SqlDataReader rdr;  
  62.             byte[] fileContent = null;  
  63.             string fileType = "";  
  64.             string file_Name = "";  
  65.             const string connect = @"Server=.;Database=Demo;User id=sa;password=wintellect;";  
  66.             using (var con = new SqlConnection(connect))  
  67.             {  
  68.                 var query = "SELECT Filerecord, Filetype, Name FROM Datafile WHERE ID = @ID";  
  69.                 var cmd = new SqlCommand(query, con);  
  70.                 cmd.Parameters.AddWithValue("@ID", id);  
  71.                 con.Open();  
  72.                 rdr = cmd.ExecuteReader();  
  73.                 if (rdr.HasRows)  
  74.                 {  
  75.                     rdr.Read();  
  76.                     fileContent = (byte[])rdr["Filerecord"];  
  77.                     fileType = rdr["Filetype"].ToString();  
  78.                     file_Name = rdr["Name"].ToString();  
  79.                 }  
  80.             }  
  81.             return File(fileContent, fileType, file_Name);  
  82.         }  
  83.     }  
  84. }   

Step 4

Now we create a "MVC4 View Page (ASPX)" named "Index.aspx".

  • In the "Solution Explorer".

  • Right-click on "Home" then select "Add" -> "New Item".

  • Select "Installed" -> "Visual C#" -> "Web" -> "MVC4 View Page (ASPX)".

    dwn2.jpg

  • Click the "Add" button.

Add the following code:

  1. <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>   
  2. <!DOCTYPE html>  
  3. <html>  
  4. <head runat="server">  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <div>  
  10.         <%  
  11.             using (Html.BeginForm("""home", FormMethod.Post, new { enctype =   
  12.            "multipart/form-data" }))  
  13.             {%>  
  14.         <input type="file" name="FileUpload1" /><br />  
  15.         <input type="file" name="FileUpload2" /><br />  
  16.         <input type="file" name="FileUpload3" /><br />  
  17.         <input type="submit" name="Submit" id="Submit" value="SendToDatabase" /><br />  
  18.         <% }%>  
  19.         <h4>  
  20.             <a href="/Home/DownloadImage">DownLoad Image from Database</a></h4>  
  21.     </div>  
  22. </body>  
  23. </html> 

The "Html.Bigenform" method opens the <form> tag. When the form is submited this request is handled by the action method.

Step 5

Create one more View Page "DownloadImage.aspx". Follow the same procedure as for Step 4:

Clipboard08.jpg

Add the following code:

  1. <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>  
  2. <!DOCTYPE html>  
  3. <html>  
  4. <head runat="server">  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <div>  
  10.         <%int Rcrd = 1; %>  
  11.         <% foreach (string file in ViewBag.Images)  
  12.            { %>  
  13.         <h4>  
  14.             <%: Html.ActionLink(file,"GetFile/"+Rcrd++) %></h4>  
  15.         <%} %>  
  16.         <%if (Rcrd == 1)  
  17.           { %>  
  18.         <h2>  
  19.             There is No file for Downloading from the Database</h2>  
  20.         <%} %>  
  21.     </div>  
  22. </body>  
  23. </html> 

In the preceding we use the "Html.ActionLink" helper. This method is not linked to the view, it creates the link with the Controller Action.

Step 6

Execute the application, press "F5":

dwn4.jpg

Browse the files and click on the "Send" button. These files are stored in the database.

dwn5.jpg

Click on the "Download Image from the Database" link then display files, click on the file for downloading.

dwn7.jpg


Display a dialog box, click on "Save".

dwn10.jpg

Step 7

When you use the "Select" command for selecting the record from the table, all the files are displayed in the database. The command is as follows:

  1. select * from Datafile

dwn9.jpg


Similar Articles