c# mvc return JSON or File from AJAX call

后端 未结 4 819
花落未央
花落未央 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.

提交回复
热议问题