ExtJS的Ajax的文件下载请求C#MVC [英] Extjs Ajax file download request C# MVC
问题描述
我想,当点击一个按钮,客户端下载存储在我的数据库文件。 我把这个Ajax请求,并把它从服务器端。
I want client to download a file stored on my db when clicked a button. I send this ajax request and take it from the server side.
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!');
},
});
},
再遇到这个code座请求。
then meet request with this code block.
C#:
public void Download(string fileID){
Response.ContentType = "application/force-download";
Response.AddHeader("Content-Disposition", "attachment; Filename=\"Logo1.jpg\"");
Response.BinaryWrite(data);
Response.End();
}
当我检查网络萤火虫,看来我的请求,这些参数成功返回。
When I checked network with firebug, it seems my request returns successfully with these parameters.
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=?=
虽然它返回成功,不能下载。我阅读了大量的问题和文章,但大部分的答案说加力下载头解决了这个问题。我怀念这一点?谢谢你。
Although it returns successful, download does not start. I read lots of questions and articles but most answers say adding force-download header solves the problem. Which point do I miss? Thanks.
推荐答案
要处理,你应该使用所提供的助手之一的下载
To handle a Download you should use one of the provided helper
- System.Web.MVC.FilePathResult
- System.Web.MVC.FileStreamResult
- System.Web.MVC.FileContentResult
大多数时候,我使用的是 System.Web.MVC.FileStreamResult
mayself。使用它像
Most times I am using the System.Web.MVC.FileStreamResult
mayself. Use it like
FileStreamResult result = new FileStreamResult(stream, contentType);
result.FileDownloadName = filename; // name of the downloaded file
更新 根据您的编辑只是一些相关信息的
您可以不使用XHR请求开始下载。但至少有两种方法可以如何做到这一点:
You cannot start download using XHR request. But there are at least two ways how you can do it:
- 如果文件路径是固定和你知道它设置
top.location.href =YourPath; Ajax调用成功处理程序中
。 [相关信息约 <一个href="http://stackoverflow.com/questions/3332756/difference-between-window-location-href-and-top-location-href">top.location.href] - 如果您动态创建的文件,并希望返回它,你应该创建一个隐藏的iframe和形式注入到它的再执行请求。
- If the file-path is fix and you know it set
top.location.href = "YourPath";
within the success handler of the ajax call. [Infos about top.location.href] - If you create the file on the fly and want to return it you should create a hidden iframe and inject a form into it that then execute the request.
这篇关于ExtJS的Ajax的文件下载请求C#MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!