从控制器RedirectToAction下载文件() [英] Download file from controller RedirectToAction()

查看:111
本文介绍了从控制器RedirectToAction下载文件()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的东西比较简单挣扎的老MVC 1.0应用程序。

I have an old MVC 1.0 application that I am struggling with something relatively simple.


  1. 我有一个观点,即允许用户上传文件。

  2. 某些服务器端处理不胜枚举。

  3. 最后,生成并自动下载到客户端的机器的新文件。

我有步骤1和2的工作。我不能得到的最后一步工作。这里是我的控制器:

I have steps 1 and 2 working. I can not get the final step to work. Here is my controller:

[AcceptVerbs(HttpVerbs.Post)]
public ViewResult SomeImporter(HttpPostedFileBase attachment, FormCollection formCollection, string submitButton, string fileName
{
    if (submitButton.Equals("Import"))
    {
        byte[] fileBytes = ImportData(fileName, new CompanyExcelColumnData());
        if (fileBytes != null)
        {
            RedirectToAction("DownloadFile", "ControllerName", new { fileBytes = fileBytes});
        }
        return View();
    }
    throw new ArgumentException("Value not valid", "submitButton");
}

public FileContentResult DownloadFile(byte[] fileBytes)
{
    return File(
                fileBytes,
                "application/ms-excel",
                string.Format("Filexyz {0}", DateTime.Now.ToString("yyyyMMdd HHmm")));
}

在code执行:

The code executes:

RedirectToAction("DownloadFile", "ControllerName", new { fileBytes = fileBytes});

但文件不会下载。建议表示欢迎和感谢提前。

but the file does not download. Suggestions welcome and thanks in advance.

推荐答案

尝试返回的 的ActionResult ,因为它是最抽象类的动作输出。的ViewResult将迫使你返回查看或PartialView,因此,返回一个文件将获得有关隐式类型converttion异常。

Try to return ActionResult, because it is the most abstract class of the output of actions. ViewResult will force you to return a View or PartialView, so, return a File will get an exception about implicitly converttion type.

[HttpPost]
public ActionResult SomeImporter(HttpPostedFileBase attachment, FormCollection formCollection, string submitButton, string fileName
{
    if (submitButton.Equals("Import"))
    {
        byte[] fileBytes = ImportData(fileName, new CompanyExcelColumnData());
        if (fileBytes != null)
        {
            return File(
                fileBytes,
                "application/ms-excel",
                string.Format("Filexyz {0}", DateTime.Now.ToString("yyyyMMdd HHmm")));
        }
        return View();
    }
    throw new ArgumentException("Value not valid", "submitButton");
}

这篇关于从控制器RedirectToAction下载文件()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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