□Ideas
Click a link to pass the file Id to the Controller method, traverse all the files in the folder, find the corresponding file based on the ID, and return the FileResult type.
File-related Model:
namespace MvcApplication1.Models{ public class FileForDownload { public int Id { get; set; } public string Name { get; set; } public string Path { get; set; } }}
Write a help class for files, traverse all files in the specified folder, and return the FileForDownload collection type. Create a Files folder in the project root directory to store the downloaded Files.
using System.Collections.Generic;using System.IO;using System.Web.Hosting;using MvcApplication1.Models;namespace MvcApplication1.Helper{ public class FileHelper { public List<FileForDownload> GetFiles() { List<FileForDownload> result = new List<FileForDownload>(); DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/Files")); int i = 0; foreach (var item in dirInfo.GetFiles()) { result.Add(new FileForDownload() { Id = i + 1, Name = item.Name, Path = dirInfo.FullName + @"\" + item.Name }); } return result; } }}
HomeController:
using System;using System.Linq;using System.Web.Mvc;using MvcApplication1.Helper;namespace MvcApplication1.Controllers{ public class HomeController : Controller { private FileHelper helper; public HomeController() { helper = new FileHelper(); } public ActionResult Index() { var files = helper.GetFiles(); return View(files); } public FileResult DownloadFile(string id) { var fId = Convert.ToInt32(id); var files = helper.GetFiles(); string fileName = (from f in files where f.Id == fId select f.Path).FirstOrDefault(); string contentType = "application/pdf"; return File(fileName, contentType, "Report.pdf"); } }}
Home/Index. cshtml View
@ Model IEnumerable <MvcApplication1.Models. FileForDownload> @ {ViewBag. Title = "Index"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}< table >@foreach (var item in Model) {<td> @ Html. displayFor (modelItem => item. id) </td> <td> @ Html. displayFor (modelItem => item. name) </td> <td> @ Html. actionLink ("Download", "DownloadFile", new {id = item. id}) </td >}</table>
References:
Download Files in ASP. net mvc 3 using Controller Action