c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
asp.net MVC

How to download the file if I’m recording the data into a database?

| | ASP-NET , CSharp , MVC

One of the viewer asked, It is simple to download the file. We have to store the file in a specified folder path and then store the file path into database.

Here, I have uploaded the files under the “Files” folder. 

I Created an ado.net entity data model using the table iDocuments and generated entity for that. 

 

Step 1: create a mvc controller, right click on the controllers folder and add home controller. Copy and paste the following code and update accordingly.  

public FileResult Download(string path)
        {
            string fileName = Path.GetFileName(path);
            string fullPath = Path.Combine(Server.MapPath("~/Files"), fileName);
            byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }

private models db = new models();
       //
        public ActionResult Index()
        {
            return View(db.iDocuments.ToList());
        } 

Step 2: Right click on the Homecontroller and create an index view. Copy and paste the following code, 

@foreach (var item in Model)
                {
item.Name
                      <a class=" btn btn-xs btn-default" title="download" href="@Url.Action("Download", "Home", new { area = "", path =item.Path })"><span class="glyphiconglyphicon-download"></span></a>

}

 Description: Using for loop I have displayed the number of files that already stored in to the database with name and file path. After I running the application, I just download the file to the browser’s download path by clicking the download button.