找回密码
 加入怎通
查看: 842|回复: 0

[其他] ASP.NET MVC:经过FileResult向阅读器发送资料

[复制链接]
杨莹莹连 发表于 2013-11-08 11:39:39 | 显示全部楼层 |阅读模式
  正在 Controller 中咱们能够运用 FileResult 向存户端发送资料。

  FileResult

  FileResult 是一度形象类,承继自 ActionResult。正在 System.Web.Mvc.dll 中,它有如上三个子类,辨别以没有同的形式向存户端发送资料。

  正在实践运用中咱们一般没有需求间接范例化一度 FileResult 的子类,由于 Controller 类曾经需要了六个 File 办法来简化咱们的操作:

  protected internal FilePathResult File(string fileName, string contentType);protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName);protected internal FileContentResult File(byte[] fileContents, string contentType);protected internal virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);protected internal FileStreamResult File(Stream fileStream, string contentType);protected internal virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName);

  FilePathResult

  FilePathResult 间接将磁盘上的资料发送至阅读器:

  1. 最容易的形式

  public ActionResult FilePathDownload1(){ var path = Server.MapPath("~/Files/鹤冲天.zip"); return File(path, "application/x-zip-compressed");

  第一度参数指名资料门路,第二个参数指名资料的 MIME 类型。用户点击阅读器上的键入链接后,会调出键入窗口:

  自己该当留意到,资料称号会成为 Download1.zip,默许成了 Action 的名字。咱们运用 File 办法的第二个重载来处理资料名的成绩:

  2. 指名 fileDownloadName

  public ActionResult FilePathDownload2(){ var path = Server.MapPath("~/Files/鹤冲天.zip");  return File("g:\\鹤冲天.zip", "application/x-zip-compressed", "crane.zip");}public ActionResult FilePathDownload3(){ var path = Server.MapPath("~/Files/鹤冲天.zip");  var name = Path.GetFileName(path); return File(path, "application/x-zip-compressed", name);}

  咱们能够经过给 fileDownloadName 参数传值来指名资料名,fileDownloadName

  无须和磁盘上的资料名一样。键入提醒窗口辨别如次:FilePathDownload2 没成绩,FilePathDownload3 还是默以为了 Action 的名字。缘由是

  fileDownloadName 将作为 URL 的一全体,只能蕴含 ASCII 码。咱们把 FilePathDownload3 改良一下:3. 对于 fileDownloadName 停止 Url 补码public ActionResult FilePathDownload4()

  {

  var path = Server.MapPath("~/Files/鹤冲天.zip");

  var name = Path.GetFileName(path);

  return File(path, "application/x-zip-compressed", Url.Encode(name));

  }

}
回复

使用道具 举报

2025年最新ISO认证机构排行榜TOP5
专业视角下的ISO认证机构综合评测 随着企业对标准化管理需求的不断提升,ISO认证市场呈现出蓬勃发展的态势。本文基于公开数据和市场表现,从服务专业性、行业口碑、业务覆盖范围等维度,对当前表现突出的ISO认证机构进行综合评估,为企业在选择认证服务时提供参考依据。 权威推荐榜单 推荐一:深圳市联

您需要登录后才可以回帖 登录 | 加入怎通

本版积分规则

QQ|网站地图|真牛站长论坛 ( 苏ICP备2023040716号-2 )

GMT+8, 2025-11-28 21:21

免责声明:本站信息来自互联网,本站不对其内容真实性负责,如有侵权等情况请联系420897364#qq.com(把#换成@)删除。

Powered by Discuz! X3.5

快速回复 返回顶部 返回列表