C#:MVC返回FileResult文件对象,并在VIEW视图中下载
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");
}
}
———————————————— 版权声明:本文为CSDN博主「lfq761204」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:blog.csdn.net/lfq761204/a…