1

In asp mvc 5, I launch a download with that code:

//jQuery
 $(document).on('click', "#download_export", function (e) {
        window.location = url_download;
    });

//c#
 public FileResult GetFile()
        {
            return File(Encoding.UTF8.GetBytes("dfdfdf dfssdfdfs"),
                   "text/plain",
                    "test.txt");
        }

It works and trigger a txt file download on client browser.

I want to do same thing by passing file content on argument from controller,

I tried:

    $(document).on('click', "#download_export", function (e) {
     $.get(url_download,
            {
                content : 'this is my content'
            }
            , function (data) {
                     console.log('works')
        });
   });

 public FileResult GetFile(string content)
        {
            return File(Encoding.UTF8.GetBytes(content),
                   "text/plain",
                    "test.txt");
        }

I saw with debugger that Action is reached but it doesn't trigger a download,

Do you have idea how to do it?

1
  • Here - public FileResult GetFile(string content) - what is the value of content when you debug? Commented Apr 11, 2015 at 12:50

2 Answers 2

1

I'm afraid that you cannot download files with ajax. Due to security reason, javascript is not allowed to access local files system. Imagine a case where js from a remote site tries to steal files on your pc.

Try:

$(document).on('click', "#download_export", function (e) {
        window.location = url_download + "?content=this is my content";
    });

Or you can create a hidden iframe on the page to download the file to avoid changing location of current window.

$(document).on('click', "#download_export", function (e) {
            $("#yourIframe").attr("src",url_download + "?content=this is my content");
        });
Sign up to request clarification or add additional context in comments.

Comments

0

If you want a dynamic download then you can use -> $.filedownload jquery plugin for those purposes. Simple usage:

var promise = $.fileDownload(url_download+"?content=yourContentHere");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.