Extjs Ajax文件下载请求C#MVC

我希望客户端在单击按钮时下载存储在我的数据库中的文件。 我发送这个ajax请求并从服务器端获取它。

EXTJS:

downloadFile: function (a, b, c) { var feed_id =this.getMyfeedwindow().down('form').getComponent('FeedId').text; Ext.Ajax.request({ url: '/Feed/Download', method: 'GET', params: { fileID: feed_id, //this.form.getComponent('file').value, }, failure: function (response) { alert('failed !'); }, success: function (response) { alert('success!'); }, }); }, 

然后用这个代码块满足请求。

C#:

  public void Download(string fileID){ Response.ContentType = "application/force-download"; Response.AddHeader("Content-Disposition", "attachment; Filename=\"Logo1.jpg\""); Response.BinaryWrite(data); Response.End(); } 

当我用firebug检查网络时,似乎我的请求使用这些参数成功返回。

 Cache-Control private Content-Disposition attachment; filename="Logo1.jpg" Content-Type application/force-download Date Wed, 09 Jan 2013 12:51:54 GMT Server Microsoft-IIS/8.0 Transfer-Encoding chunked X-AspNet-Version 4.0.30319 X-AspNetMvc-Version 4.0 X-Powered-By ASP.NET X-SourceFiles =?UTF-8?B?RTpcVXRrdUNhblxQcm9qZWN0c1xURlNcQlRPTVxCVE9NXEZlZWRcRG93bmxvYWQ=?= 

虽然它返回成功,但下载无法启动。 我阅读了很多问题和文章,但大多数答案都说添加force-download header可以解决问题。 我想念哪一点? 谢谢。

要处理下载,您应该使用提供的帮助程序之一

  • System.Web.MVC.FilePathResult
  • System.Web.MVC.FileStreamResult
  • System.Web.MVC.FileContentResult

大多数时候我使用的是System.Web.MVC.FileStreamResult 。 用它就好

 FileStreamResult result = new FileStreamResult(stream, contentType); result.FileDownloadName = filename; // name of the downloaded file 

根据您的编辑 更新 一些信息

您无法使用XHR请求开始下载。 但至少有两种方法可以做到:

  • 如果文件路径是修复的,你知道它设置top.location.href = "YourPath"; 在ajax调用的成功处理程序中。 [关于top.location.href的信息 ]
  • 如果你动态创建文件并想要返回它,你应该创建一个隐藏的iframe并在其中注入一个表单然后执行请求。

经过一些搜索,我发现location.href做了同样的事情并打开了一个下载对话框。 应该将相同的标头添加到来自服务器的响应中。 但是,我仍然不知道为什么其他方法不起作用。

 var feed_id = this.getMyfeedwindow().down('form').getComponent('FeedId').text; location.href = '/Feed/Download?fileID=' + feed_id; 

这解决了我的问题。