如何从Asp.Net MVC Web应用程序中的FileStremResult对象获取文件?

时间:2015-10-30 08:18:37

标签: c# asp.net-mvc

我有表格的Asp.Net MVC Web应用程序。当我提交表单应用程序运行方法:

[HttpPost]
public ActionResult MyMethod(MyViewModel model)
{
    FileStreamResult document = CreateDocument(model);
    return document;
} 

浏览器在同一选项卡中打开生成的文件(PDF)。 我不想打开这个文件,而是想把它下载到磁盘上。 如何实施这一行动?

2 个答案:

答案 0 :(得分:3)

您需要告诉浏览器它是下载文件而不是文件。

您可以通过设置2个标题(内容类型和内容处置),然后将PDF写入响应流来完成此操作。

[HttpPost]
public ActionResult MyMethod(MyViewModel model)
{

     HttpResponseBase response = ControllerContext.HttpContext.Response;

    response.ContentType = "application/pdf";
    response.AppendHeader("Content-Disposition", "attachment;filename=yourpdf.pdf");

    FileStreamResult document = CreateDocument(model);
    //Write you document to response.OutputStream here
    document.FileStream.Seek(0, SeekOrigin.Begin);
    document.FileStream.CopyTo(response.OutputStream, document.FileStream.Length);

    response.Flush();

    return new EmptyResult();
} 

答案 1 :(得分:0)

你应该返回一个FileStreamResult(这将强制与“FileDownloadName”一起下载。通过将ActionResult指定为方法返回值,你可以灵活地返回其他东西(HttpStatusCodes,View()或者内容()的)。

public ActionResult DownloadSomeFile()
    {
        using (var ms = new MemoryStream())
        {
            var response = GetMyPdfAsStream(); // implement this yourself
            if (response is StreamContent)
            {
                var responseContent = response as StreamContent;
                await responseContent.CopyToAsync(ms);
                byte[] file = ms.ToArray();
                MemoryStream output = new MemoryStream();
                output.Write(file, 0, file.Length);
                output.Position = 0;

                return new FileStreamResult(output, "application/pdf") { FileDownloadName = fileName };
            }
            else
            {
                return Content("Something went wrong: " + response.ReasonPhrase);
            }
            return null;
        }

    }