Extjs Ajax文件下载请求C#MVC

前端之家收集整理的这篇文章主要介绍了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标题解决了这个问题.我想念哪一点?谢谢.

解决方法

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

> 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并在其中注入一个表单然后执行请求.

猜你在找的Ajax相关文章