1

When I try to Download file via ajax json MVC controller not working. not getting the MIME response. Just renders as text in window. I tried all options mentioned in forums but no luck. Please help. The controller sends the proper file back but the javascript ajax renders it as json I think. I want to get the "Save" or "Open" file response header prompt for file when I click the download button.

 $("#btnDownloadEDIFile").bind("click", function (e)
    {
        e.preventDefault();
        displayAjaxLoading(true);

        $.ajax({
            type: 'POST',
            dataType: "json",
            async: false,
            contentType: 'application/json; charset=utf-8',
            url: '@Url.Action(MVC.AccountsPayable.StagedInvoice.DownloadFile())',
            data: JSON.stringify({ StagedFileId: $('#StagedFileId').val() , FilePath:      $('#FilePath').val() , SourceFileName: $('#SourceFileName').val() }),
            success: function (result) {
                //alert(result);
                if (result != "") {
                    displayNotoficationError([result]);
                }
                else {

                }

            },

            error: function (result) {
                //debugger;
                alert(result);
                displayNotoficationError([result]);
            }
        });
    });

When I execute this it renders as text on window and also throws a ajax error in javascript.

Here's controller code

  public virtual ActionResult DownloadFile(Nullable<int> StagedFileId, string FilePath, string SourceFileName)
    {

        string _FullPath = _WebApplicationConfiguration.SourceStagedInvoiceFileFolder + FilePath;
        if (System.IO.File.Exists(_FullPath))
        {

            HttpContext.Response.ClearContent();
            HttpContext.Response.ContentType = "application/octet-stream";

            HttpContext.Response.AddHeader("content-disposition",

                                                   "attachment; filename=" + SourceFileName);

            HttpContext.Response.BinaryWrite(System.IO.File.ReadAllBytes(_FullPath));
            return File(_FullPath, "text/octet-stream", SourceFileName);

        }
        else
        {

            return Content("");
        }
    }
tereško
  • 58,060
  • 25
  • 98
  • 150
Programmer
  • 61
  • 2
  • 3
  • 5

1 Answers1

0

I know this is not exactly what you are trying to do, but I have been pretty happy with a totally different approach. This method will force the Download/Open dialog no matter how the file is linked to or what browser is used. All you have to do is make sure all the files that you want this behavior on must be in a specified folder, in this case /Library.

Add this to your Global.asax file in either classic Asp.Net or MVC.

protected void Application_BeginRequest()
{
    if (Request.Path.Contains("/Library/") && (File.Exists(Request.PhysicalPath)))
    {
        var fileInfo = new FileInfo(Request.PhysicalPath);

        Response.Clear();
        Response.TransmitFile(Request.Path);
        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
        Response.AddHeader("Content-Length", fileInfo.Length.ToString());
        Response.Flush();
        Response.End();
    }
}

I got the idea for this from this site, but I can't find the link to give credit. Sorry.

Trey Gramann
  • 2,004
  • 20
  • 23