0

I have the controller code below:

public FileResult DownloadFileParaView()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(@"MyPath");
    string fileName = "MyFileName";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

How can I call it from JavaScript to return my file? Does I have to copy the file to project content?

Gugalaxia
  • 3
  • 1
  • Are you trying to trigger a download prompt, or just return a file for your JavaScript code to interpret in some fashion? – Tieson T. Feb 05 '20 at 22:21
  • I just want to open the typical download window where client can save the file to his PC – Gugalaxia Feb 05 '20 at 22:22
  • the fileName also need to have the extension – Ivan-San Feb 05 '20 at 22:22
  • 1
    This is an HTTP endpoint, so call it like you would any other HTTP endpoint. –  Feb 05 '20 at 22:22
  • could any of you provide some code example please? – Gugalaxia Feb 05 '20 at 22:24
  • There are *countless* examples of that already. People have used JavaScript to call HTTP endpoints for over 20 years. Google "javascript ajax" or "javascript get http" or "javascript fetch". You get the idea. –  Feb 05 '20 at 22:27
  • Also google "site:stackoverflow.com javascript fileresult", and notice you'll get some results. –  Feb 05 '20 at 22:30

1 Answers1

1

Assuming you're calling this from within a view, it's relatively simple:

window.location.href = '@Url.Action("DownloadFileParaView")';

This would be in a script tag within the view where you want to trigger the download.

Tieson T.
  • 20,774
  • 6
  • 77
  • 92