Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file from controller RedirectToAction()

Tags:

c#

asp.net-mvc

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

  1. I have a view that allows the user to upload a file.
  2. Some server side processing goes on.
  3. Finally, a new file is generated and downloads automatically to the client's machine.

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")));
}

The code executes:

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

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

like image 359
Seany84 Avatar asked Nov 21 '25 19:11

Seany84


2 Answers

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");
}
like image 157
Felipe Oriani Avatar answered Nov 24 '25 10:11

Felipe Oriani


Why do RedirectToAction? Can you return File from SomeImporter action, just change the return type of SomeImporter to FileContentResult.

like image 45
Sergey Avatar answered Nov 24 '25 09:11

Sergey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!