处理(jQuery)Ajax调用中返回的ASP.NET MVC FileResult [英] Handling an ASP.NET MVC FileResult returned in an (jQuery) Ajax call

查看:546
本文介绍了处理(jQuery)Ajax调用中返回的ASP.NET MVC FileResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:
我想让我的用户在我的网页上下载文件.我想打开一个新窗口,并在其中显示或下载文件.

Goal:
I want to let my users download a file on my webpage. I want a new window to open and the file to be either displayed or downloaded there.

我的实现方式:
但是,此文件首先必须在服务器端生成,这可能需要一段时间.当用户单击按钮下载文件时,我进行了ajax调用并显示等待的动画,直到得到响应为止.处理该调用的控制器操作将生成文件(PDF)并返回FileResult.现在,在我的ajax调用javascript的succes函数中,我得到了文件数据.

My implementation:
This file however, first has to be generated on the server-side, which might take a while. When the user clicks the button to download the file, I do an ajax call and show a waiting animation until I get a response. The controller action that handles the call will generate the file (PDF) and return a FileResult. Now in the succes function of my ajax call back in javascript, I get the file data.

问题:我不知道该如何处理这些数据才能将其提供给用户.

Problem: I have no Idea what I'm supposed to do with this data to get it to the user.

解决方法:
现在,我使用一种变通方法,在该方法中,我不通过ajax调用返回文件,而是将其存储在会话中.在成功函数中,我执行window.open("/controller/getPDFFromSession")会下载文件.但是,我不希望将会话用于此类事情.

Workaround:
Right now I use a workaround where I do not return the file in the ajax call, but store it in session. In the succes function I do window.open("/controller/getPDFFromSession") which will download the file. However, I prefer not to use the session for these kind of things.

谢谢.

推荐答案

问题:我不知道该如何处理这些数据才能将其提供给用户.

Problem: I have no Idea what I'm supposed to do with this data to get it to the user.

由于这个原因,您不应该使用AJAX下载文件.您可以执行以下操作:

You shouldn't use AJAX for downloading files for this reason. You could do the following:

  1. 用户单击下载按钮
  2. 使用javascript,您会看到一些进度图像,通知他必须等待
  3. 使用JavaScript生成隐藏的iframe并将其注入到DOM中,该iframe的src属性指向应该生成文件的控制器操作
  4. 加载iframe后,您可以隐藏进度图像
  1. The user clicks on the download button
  2. Using javascript you show some progress image informing him that he will have to wait
  3. Using javascript you generate and inject a hidden iframe into the DOM having its src property pointing to the controller action supposed to generate the file
  4. Once the iframe is loaded you could hide the progress image

这篇关于处理(jQuery)Ajax调用中返回的ASP.NET MVC FileResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆