正在 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));
}
} |