0

There's an interesting thread on stackoverflow about it: ASP.NET MVC: returning plaintext file to download from controller method

This post explains how to show the content of a txt file on a url, but not how to save the content of that url to the client's disk.

Is there any possibility to save (on the client side) a file that (pratically) doesn't exist? There's just plain text, and the idea would be to download this plain text to a TXT file.

Community
  • 1
  • 1
Luis Gouveia
  • 8,334
  • 9
  • 46
  • 68
  • @Rhumborl, I am sorry but I do not agree with you. The proposed solution on your link needs the file to have a path (or to exist physically on the server-side). What I am searching for is a solution that avoids the existance of such file. – Luis Gouveia Feb 02 '16 at 12:34
  • 1
    You have no control over the clients file system. You have to return a physical file to the browser and let the user save it to their system. –  Feb 02 '16 at 12:41
  • 3
    The accepted answer to that question states: "Return a FileResult or FileStreamResult from your action, depending on whether the file exists or you create it on the fly." So it does not need to physically exist on the server – Rhumborl Feb 02 '16 at 12:42

1 Answers1

1

This is how I send PDF invoice to the client:

      string contentType = "application/pdf";
      byte[] bytes = invoice.Data;
      FileContentResult fileResult = new FileContentResult(bytes, contentType);
      fileResult.FileDownloadName = invoice.FileName;
      return fileResult;

This does not need the file on the disk. Note that what is crucial is the Content Type. This is what determines how the client browser handles the response. If you have a text file and you deliver it to the client with Content Type set to "text/plain" (or alike), it might just happen that the client browser will display the text in the browser's tab.

In order to invoke the download dialog, use

string contentType = "application/octet-stream";

This will tell the browser that you are sending "something binary", thus forcing "most of the normal browsers" to download it.

Wapac
  • 4,058
  • 2
  • 20
  • 33
  • Thank you @Wapac, this one is a more complete answer than the other one: http://stackoverflow.com/questions/730699/how-can-i-present-a-file-for-download-from-an-mvc-controller – Luis Gouveia Feb 02 '16 at 13:43