Download file from controller RedirectToAction ()

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

  • I have a view that allows the user to upload a file.
  • Some server sides are still processing.
  • Finally, a new file is created and automatically downloaded to the client machine.

I have steps 1 and 2. I cannot get the last 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")));
}

      

The code is executed:

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

      

but the file doesn't load. Suggestions are welcome and thanks in advance.

+3


source to share


2 answers


Try to return ActionResult

because this is the most abstract class of action output. ViewResult will force you to return a View or PartialView, so returning a file will get an exception from the implicit conversion 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");
}

      

+4


source


Why RedirectToAction? You can return a file from the SomeImporter activity, just change the return type of SomeImporter to FileContentResult.



+2


source







All Articles