Sirmais
Sirmais

Reputation: 128

Razor MVC Controller Download file

I have a controller like the code below and I would like to know how to call this using Razor because @Url.Action("GetFileFromDisk") does not work as expected it just crashes. If it is possible could you point out my mistake here? Or maybe suggest a better way to force on click to download the file

public FilePathResult GetFileFromDisk()
{
  string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
  string fileName = "test.txt";
  return File(path + fileName, "text/plain", "test.txt");
}

Thanks in advance.

Update

the Error message I get is

The webpage at http://mypage/Support/GetFileFromDisk might be temporarily down or it may have moved permanently to a new web address. Error code: ERR_INVALID_RESPONSE`

Upvotes: 0

Views: 2293

Answers (2)

Roman Ryba
Roman Ryba

Reputation: 53

i think you should be using FileResult if you return File insted of FilePathResult

or use the FilePathResult as return

public FilePathResult GetFileFromDisk() { string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/"; string fileName = "test.txt"; return new FilePathResult(Path.Combine(path, fileName), System.Net.Mime.MediaTypeNames.Application.Octet); }

Upvotes: 0

Andre Pena
Andre Pena

Reputation: 59336

To force a file download, you should probably use octet-stream. It's up to the client (browser) to determine whether to download or display content, but octet-stream is normally downloaded, no matter what. You should also use Path.Combine instead of manually concatenating the filename with the path.

public FilePathResult GetFileFromDisk()
{
  string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploads/");
  string fileName = "test.txt";
  return File(Path.Combine(path,fileName), "application/octet-stream", "test.txt");
}

edit, now that you've given the actual error:

This "might be temporarily down" message means no route could be found in your application that matches the given URL. There's probably something wrong with your URL.

Tips:

  1. Check if you can reach actions that are sibling to "GetFileFromDisk" using the same URL pattern.
  2. Review your routes.
  3. Install Glimpse so you can debug your routes.

Upvotes: 1

Related Questions