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类型】。

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐