FileResult是一个抽象类,有3个继承子类:FilePathResul、FileContentResult、FileStreamResult,表示一个文件对象,三者区别在于,FilePath 通过路径传送文件到客户端,FileContent 通过二进制数据的方式,而FileStream 是通过Stream(流)的方式来传送。Controller为这三个文件结果类型提供了一个名为File的重载方法。
示例代码:
using System.Web.Mvc;
using System.IO;
namespace FileResultTest.Controllers
{
public class FileResultTest: Controller{
public FilePathResult DownloadFileByPath() {
//文件路径必须是绝对路径。
string filePath = Server.MapPath("~/Content/test.pdf");
return File(filePath, "application/x-zip-compressed","test.pdf");
}
public FileContentResult DownloadFileByContent() {
string filePath = Server.MapPath("~/Content/test.pdf");
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
return File(bytes, "application/x-zip-compressed","test.pdf");
}
public FileStreamResult DownloadFileByStream() {
string filePath = Server.MapPath("~/Content/test.pdf");
Stream stream = new FileStream(filePath, FileMode.Open);
return File(stream,"application/x-zip-compressed","test.pdf");
}
}
}
File方法的第二个参数为文件内容的MIME类型,可以参考【文件的MIME类型】。