asp.net MVC

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

How to download the file if I’m recording the data into a database?, someone asked me to explain?

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. 

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

 

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. 

 

download the file from folder csharp

Post your comments / questions