Uploading Downloading PDF Files In ASP.NET MVC Using SQL Server
Follow Github Accunt for Complete Code
https://gist.github.com/Dhan777/cf360ff93cbe423581b0f0aa9091fdeb
Many times, we need to work with the file and storing the physical files on the Server, which is very difficult because it will consume lots of memory of the Server. Thus, in this article, we will learn, how to upload the files in the binary format into the database and download from the database with the help of ASP.NET MVC, using FileResult. Thus, let's learn step by step so the beginners can also understand..
Step 1 - Create MVC Application.
- create a New ASPMVC4 Application Named "MvcApplication5"
- Go to File->New->Project->ASP.NET MVC4 Web Application .Then Provide the Project Name as you wish.After clicking, the following window will appear :
Step 2 - Create Model Class
Now, let us create the model class file, named EmployeeModel.cs, by right clicking on Models folder.
Go to Solution Explorer -> Right Click on Models Folder ->Add -> Class ->Write the Name of class EmployeeModel.cs class :
The code snippet of EmployeeModel.cs will look like-
- public class EmployeeModel
- {
- public int ID { get; set; }
- public string FileName { get; set; }
- public byte [] FileContent { get; set; }
- public HttpPostedFileBase Files { get; set; }
- }
Step 3 - Create Table and Stored Procedure
Now, create the stored procedure and the table to store the uploaded files in binary format and display back to the user's view. Use the script, given below, to create the table named FileDetails as-
- CREATE TABLE [dbo].[FileDetails](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [FileName] [varchar](60) NULL,
- [FileContent] [varbinary](max) NULL
- ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Create the stored procedure to insert the file details, using the script, given below-
- Create Procedure [dbo].[AddFileDetails]
- (
- @FileName varchar(60),
- @FileContent varBinary(Max)
- )
- as
- begin
- Set NoCount on
- Insert into FileDetails values(@FileName,@FileContent)
- End
To get the uploaded file details, use the code, given below-
- CREATE Procedure [dbo].[GetFileDetails]
- (
- @Id int=null
- )
- as
- begin
- select Id,FileName,FileContent from FileDetails
- where Id=isnull(@Id,Id)
- End
Step 4 - Add DataLayer Class
Now, create the DataLayer Class to Create the Connection With DataBase and Methods to Upload and Download Files From Database. Use the script, given below, to create the DataLayer Class named , Details as-
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data.SqlClient;
- using System.Configuration;
- using Dapper;
- using System.Data;
- using System.Web.Mvc;
- namespace MvcApplication5.Models
- {
- public class DataLayer
- {
- SqlConnection Con; string s_Con;
- public DataLayer()
- {
- Connectin();
- }
- private void Connectin()
- {
- s_Con = ConfigurationManager.ConnectionStrings["Db"].ToString();
- Con = new SqlConnection(s_Con);
- if (Con.State == System.Data.ConnectionState.Open)
- {
- Con.Close();
- }
- Con.Open();
- }
- public List<EmployeeModel> GetFileList()
- {
- List<EmployeeModel> DetList = new List<EmployeeModel>();
- DetList = SqlMapper.Query<EmployeeModel>(Con, "GetFileDetails", commandType: CommandType.StoredProcedure).ToList();
- return DetList;
- }
- public bool SaveFileDetails(EmployeeModel objDet)
- {
- try
- {
- DynamicParameters Parm = new DynamicParameters();
- Parm.Add("@FileName", objDet.FileName);
- Parm.Add("@FileContent", objDet.FileContent);
- Con.Execute("AddFileDetails", Parm, commandType: System.Data.CommandType.StoredProcedure);
- return true;
- }
- catch (Exception E) { return false; }
- }
- }
- }
Step 5 - Add Controller Class
Now, let us add ASP.NET MVC controller, as shown in the screenshot, given below-
After clicking Add button, it will show in the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller . After modifying the code of Homecontroller class, the code will look like-
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcApplication5.Models;
- using Dapper;
- using System.IO;
- namespace MvcApplication5.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View(new DataLayer().GetFileList());
- }
- public ActionResult Upload()
- {
- return View();
- }
- [HttpPost]
- public string Upload(EmployeeModel E)
- {
- String FileExt = Path.GetExtension(E.Files.FileName).ToUpper();
- if (FileExt == ".PDF")
- {
- Byte[] data = new byte[E.Files.ContentLength];
- E.Files.InputStream.Read(data, 0, E.Files.ContentLength);
- E.FileName = E.Files.FileName; ;
- E.FileContent = data;
- if (new DataLayer().SaveFileDetails(E))
- {
- return string.Format("<script>alert('File Uploaded');location.assign('/Home/Index');</script>");
- }
- else
- {
- return string.Format("<script>alert('Error Occured');location.assign('/Home/Index');</script>");
- }
- }
- else
- {
- return string.Format("<script>alert('Invalid File ');location.assign('/Home/Index');</script>");
- }
- }
- [HttpGet]
- public FileResult DownLoadFile(int id)
- {
- List<EmployeeModel> ObjFiles = new DataLayer().GetFileList();
- var FileById = (from FC in ObjFiles
- where FC.ID.Equals(id)
- select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();
- return File(FileById.FileContent, "application/pdf", FileById.FileName);
- }
- }
- }
The preceding code snippet explained everything to upload and download PDF files from the database. I hope, you have followed the same.
Step 6 - Create strongly typed View
Right click on View folder of the created Application and create two strongly typed views; one is to upload the files by choosing EmpModel.cs class and Partial View by choosing EmployeeModel class to display the uploaded files. The code snippet of the view looks like-
FileUpload.cshtml
- @model MvcApplication5.Models.EmployeeModel
- @{
- ViewBag.Title = "www.compilemode.com";
- }
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
- @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
- {
- @Html.AntiForgeryToken()
- <div class="form-horizontal">
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
- @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Upload" class="btn btn-primary" />
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10 text-success">
- @ViewBag.FileStatus
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-8">
- @Html.Action("Index", "Home")
- </div>
- </div>
- </div>
- }
Index.cshtml
- @model IEnumerable<MvcApplication5.Models.EmployeeModel>
- <table class="table table-bordered">
- <tr>
- <th class="col-md-4">
- @Html.DisplayNameFor(model => model.FileName)
- </th>
- <th class="col-md-2"></th>
- </tr>
- @foreach (var item in Model) {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.FileName)
- </td>
- <td>
- @Html.ActionLink("Downlaod", "DownLoadFile", new { id=item.Id })
- </td>
- </tr>
- }
- </table>
Step 7 : Add Connection String in Web.config File:
<add name="db" connectionString="Data Source=DHANANJAY/SQLExpress;User Id=sa;Password=1;Initial Catalog=Demo" providerName="System.Data.SqlClient" />
Now we have done all coding to upload files .
Step 8 : Now run the application.
Step 8 : Now run the application.
No comments:
Post a Comment