MVC3-如何输出要下载的文件而不先将其保存在服务器上? [英] MVC3 - How to output a file to download without saving it on the server first?

查看:112
本文介绍了MVC3-如何输出要下载的文件而不先将其保存在服务器上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,可以通过使用正确的标头回显文件来将文件返回到浏览器.您无需事先在服务器上保存它的副本.

In PHP, it is possible to return a file to the browser by echoing it out with the correct header. You do not need to save a copy of it prior on the server.

因此,假设我有大量数据希望作为excel文件返回-使用OpenXML创建数据结构后,如何在不首先将其保存在服务器上的情况下将文件提供给用户?

So assuming I have a bunch of data I wish to return as a excel file - after creating the data structure using OpenXML, how can I serve the file to the user without saving it on the server first?

推荐答案

将数据写入流中,并通过

Write your data to a stream and return it from your controller action method in a FileStreamResult by setting the FileStream, ContentType and FileDownloadName properties.

    [HttpGet]
    public FileStreamResult MyFile()
    {
        var fileStreamResult = new FileStreamResult (GetMyContentAsStream(), "my/content-type-here");
        fileStreamResult.FileDownloadName = "my-file-download-name.here";

        return fileStreamResult ;
    }

更新: 这样做的捷径是使用 Controller.File ()方法.

Update: A short cut for doing this, is to use the Controller.File() method.

    [HttpGet]
    public FileStreamResult MyFile()
    {
        return File(GetMyContentAsStream(), "my/content-type-here");
    }

这篇关于MVC3-如何输出要下载的文件而不先将其保存在服务器上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆