ASP.NET MVC实现文件下载
思路
点击一个链接,把该文件的Id传递给控制器方法,遍历文件夹所有文件,根据ID找到对应文件,并返回FileResult类型。
与文件相关的Model:
namespace MvcApplication1.Models { public class FileForDownload { public int Id { get; set; } public string Name { get; set; } public string Path { get; set; } } }
文件帮助类
写一个针对文件的帮助类,遍历指定文件夹的所有文件,返回FileForDownload集合类型。在项目根目录下创建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 }); i++; } 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中:
@model IEnumerable<MvcApplication1.Models.FileForDownload> @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <table> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Id) </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.ActionLink("下载", "DownloadFile", new { id = item.Id }) </td> </tr> } </table>
到此这篇关于ASP.NET MVC实现文件下载的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
SQL Server数据库连接 Web.config如何配置
以下的文章主要描述的是Web.config正确配置SQL Server数据库连接的实际擦步骤。我们以图文结合的方式对其有个更好的说明,需要的朋友可以参考下2015-10-10一个Asp.Net的显示分页方法 附加实体转换和存储过程 带源码下载
现在自己写的webform都不用服务器控件了,所以自己仿照aspnetpager写了一个精简实用的返回分页显示的html方法,其他话不说了,直接上代码2012-10-10asp.net中使用cookie与md5加密实现记住密码功能的实现代码
虽然.net内置了登陆控件,有记住密码的功能,但还是想自己实践一下,以下代码主要应用了COOKIE,包括安全加密的过程等2013-02-02详解在Azure上部署Asp.NET Core Web App
这篇文章主要介绍了详解在Azure上部署Asp.NET Core Web App,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-12-12ASP.NET编程时遇到GridView的一个问题 激发了未处理的事件"PageIndexChanging&q
今天在写代码的时候遇到一个很郁闷的问题,就是在ASP.NET中通过编程创建SqlDataSource然后绑定给GridView,在启用了 GridView自身的分页功能之后,点击分页页码会出现错误提示:GridView“GridView1”激发了未处理的事件"PageIndexChanging"……2010-04-04asp.net 合并GridView中某列相同信息的行(单元格)
合并GridView中某列相同信息的行(单元格)2009-11-11
最新评论