0

I have a controller with a method for downloading file. Without code, all I need is to go to this link:

http://localhost:1186/Content/MyFolder/file1.exe

and the file gets downloaded.

I tried to do this with code like this:

Response.Redirect(Server.MapPath("~\\Content\\MyFolder\\file1.exe"));

But the breakpoint passes through this line and nothing happens. I think the problem is I'm using Server.MapPath, but how else would I do this?

petko_stankoski
  • 10,459
  • 41
  • 127
  • 231
  • Server.MapPath return the physical path of the resource, try Response.Redirect("~\\Content\\MyFolder\\file1.exe"); – MSUH Jun 07 '12 at 06:59
  • This related SO question about downloading files with MVC may be helpful, http://stackoverflow.com/questions/5826649/returning-a-file-to-view-download-in-mvc – Despertar Jun 07 '12 at 07:18

1 Answers1

0

you can do something like this

create an action

public ActionResult RedirectToDownload()
{
    return View();
}

and then on the view with JavaScript on load redirect to your URL

$(document).ready(function() {
  window.navigate("~/Content/MyFolder/file1.exe");
});

you might also use this

public ActionResult Index()
{
    return Redirect("~/Content/MyFolder/file1.exe");
}
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
  • I don't see the point of having the controller send the user to a view which redirects the user again. It's the controller's primary job to perform the redirections. – Despertar Jun 07 '12 at 07:13
  • you still need a view unless you are dowloading the file directly from the action – COLD TOLD Jun 07 '12 at 07:14
  • @Despertar http://blogs.msdn.com/b/rickandy/archive/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix.aspx – COLD TOLD Jun 07 '12 at 07:20
  • window.navigate don't works in all the browsers(ex. firefox) as well the "~" symbol. – VJAI Jun 07 '12 at 09:31
  • @Mark have not seen a browser that would not recognize ~ – COLD TOLD Jun 07 '12 at 15:35
  • Well I'm not whether any browser would recognize "~", when you try window.location = "~/Content/MyFolder/file1.exe" – VJAI Jun 07 '12 at 15:40
  • Well I'm stopping here! May be you should go and check before posting comments. – VJAI Jun 07 '12 at 15:42