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!');
},
});
},
然后用这个代码块来满足请求。
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();
}
当我使用firebug检查网络时,似乎我的请求成功返回了这些参数。
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
自己。使用它像
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
更新只是一些信息根据您的编辑
Update Just some Infos based on your edit
您无法使用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调用的成功处理程序中。 [关于 top.location.href ] - 如果您即时创建文件并希望返回,那么您应该创建一个隐藏的iframe,然后向其中注入一个表单,然后执行该请求。 li>
- 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屋!