1

I send a request via ajax and if response data success is true, I make a GET request in ajax success function:

success: function (data, status) {

                if (!data["Success"]) {
                    alert("Error occurred: Cant read data properly," + data["Message"]);
                    return null;
                }
                window.location = '/Home/downloadanddelete?file=output.' + data["filetype"];

The problem is when Get request posted to controller the response is: enter image description here

As you see the file request url is:"http://localhost:53091/Home/downloadanddelete?file=output.xml"

And I expect download this "output.xml" file and return the referrer page url.

here is download method in controller:

[HttpGet]
        public ActionResult downloadanddelete(string file)
        {
            string fullName = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data", file);
            if (System.IO.File.Exists(fullName))
            {
                return File(fullName, "application/xml");
            }
            return View("Index");
        }

What is it wrong here?

TyForHelpDude
  • 4,828
  • 10
  • 48
  • 96

2 Answers2

3

You'll need to change two things. In the server code, you need to send a Content-Disposition header to indicate the content is an "attachment". Add these lines before sending the file:

var cd = new System.Net.Mime.ContentDisposition
{
    FileName = "filename.xml", 
    Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());

Secondly, you ought to use window.location.assign(...); instead of setting window.location for a more seemless experience in the browser.

Jacob
  • 77,566
  • 24
  • 149
  • 228
2

You can use the Header type "Content-Disposition" to tell the browser to preferably download and save the file, instead of displaying it. There is some information on it here: https://stackoverflow.com/a/20509354/1862405

For your specific case, you'd want to use the attachment disposition, which you can add to your controller action with AddHeader:

HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=\"download.xml\"");

Another thing is that Firefox might overrule this, but you can set up for file types how it should handle them.

Community
  • 1
  • 1
mtaanquist
  • 506
  • 4
  • 16