c# mvc return JSON or File from AJAX call

后端 未结 4 816
花落未央
花落未央 2021-01-14 00:30

I have something like this in my View:

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

        $.ajax({
          


        
相关标签:
4条回答
  • 2021-01-14 00:56

    Your code will never work because you can't stream binary data to an Ajax request - you don't have a normal response context to write to.

    You can take several approaches:

    1. If the validation passes, simply return a new link to another handler that will stream the data to the user. You would then read this link on your Javascript callback function and open it in a new window.
    2. Use an IFRAME, as DAN Natic suggested above.
    3. More complicated: Base64-encode the binary data and return it as part of the Json result. Read the base64-encoded file, decode it using Javascript (plenty of libraries to do this are found online) and do something* with the result.

    * I am not sure it's possible to do anything in the case of ZIP files. You may be able to display PDF files inline inside the browser using this technique but highly doubt that it will work on all browsers. My advise is to go with option 1.

    0 讨论(0)
  • 2021-01-14 01:14

    Ajax: window.location = '/Home/download';

    c#:

            public FileResult download()
            {
               return File("~/" + path, "application/pdf", string.Format(fileName));
            }
    
    0 讨论(0)
  • 2021-01-14 01:17

    Have you considered passing back JSON with a file Url?

    If the file is successfully found/created. Send back a JSON result with the link to the file. Then in javascript use windows.location to retrieve the file. When there is an error, the JSON result will contain the error information and this info can be displayed to the user. For this to work, you'll need to create another endpoint (action) that can stream the file.

    0 讨论(0)
  • 2021-01-14 01:20

    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.

    0 讨论(0)
提交回复
热议问题