Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# mvc return JSON or File from AJAX call

I have something like this in my View:

        var url = '@Url.Action("DownloadZip", "Program")' + '?programNums=' + selectedRow;

        $.ajax({
            url: url,
            dataType: 'json',
            async: false,
            success: function (data) {
                if (data != "Successful") {
                    alert(data);
                }
            }
        });

The controller can return a File or can return a JSON result if there was an error. Haven't been able to get them both work together.

Here is what it looks like:

    public ActionResult DownloadZip(string programNums)
    {

        if(string.IsNullOrEmpty(programNums))
        {
          return Json("Error, blank info sent.", JsonRequestBehavior.AllowGet);
        }            

        var memoryStream = new MemoryStream();

        using (var zip = new ZipFile())
        {
            zip.AddFile("C:\\sitemap.txt");
            zip.Save(memoryStream);
        }

        memoryStream.Seek(0, 0);
        return File(memoryStream, "application/octet-stream", "archive.zip");

    }

What I am seeing is that the ajax call needs a JSON value back. Since in my case, it returns a File, it cannot work. Anyway to handle what I am doing to where it can give back a JSON or a File from the ajax call.

like image 222
Nate Pet Avatar asked Feb 18 '23 03:02

Nate Pet


1 Answers

I think you are going to run into a lot of problems with this implementation. You actually cannot upload or download files via AJAX. See the link below.

How to download file from server using jQuery AJAX and Spring MVC 3

You should use one of the two implementations shared in the question pasted above. If you use the IFRAME method, you may be able to use jQuery to check when the document is done and whether or not it succeeded.

EDIT: You can just throw a server exception (500). How you handle the 500 from the IFRAME is up to you.

like image 181
Dan Natic Avatar answered Feb 21 '23 02:02

Dan Natic