重定向响应下载文件 [英] Redirect response to download file
问题描述
我有我打电话用这个很基本的js代码的通用处理程序:
I have a generic handler that I call using this very basic js code:
var formData = new FormData();
formData.append("fileId", this.model.get("id"));
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/DownloadFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
// Do something here?
}
}
xhr.send(formData);
我的通用处理程序代码似乎看行给我。基本上我试图建立响应头,我还以为这时候返回的处理程序,将开始文件的下载
My generic handler code seems to look ok to me. Basically I'm attempting to build the response header and I thought that when this handler returned it would begin the download of the file.
处理代码:
var fileId = context.Request.Form["fileId"];
// File stored in the db as a byte array
var file = (from f in dataContext.OneEVA_Docs_File_Storages
where Equals(f.ID, fileId)
select f).FirstOrDefault();
context.Response.Clear();
context.Response.AddHeader("Content-Type", file.ContentType);
context.Response.AddHeader("Content-Length", file.ContentLength.ToString());
context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}; size={1}", file.Name, file.ContentLength));
context.Response.BinaryWrite(file.File_Image.ToArray());
context.Response.Flush();
context.Response.End();
的
XHR
请求完成后确定。这里是响应头,我回去:
The XHR
request completes ok. Here is the response header I get back:
Cache-Control:private
Connection:Close
Content-Disposition:attachment; filename=Mikes File; size=1860113
Content-Length:1860113
Content-Type:image/jpeg
Date:Wed, 16 May 2012 14:08:01 GMT
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319
我是什么失踪?我在做什么错了?
What am I missing? What am I doing wrong?
推荐答案
这不会开始在浏览器中下载。这是很难用一个POST请求来实现。它不可能是一个GET请求,如果你只传递一个ID?然后,你只是做
That won't start a download in the browser. It's difficult to achieve using a POST request. Can it not be a GET request if you are only passing an id? Then you just do
document.location.href = '/genericHandlers/DownloadFile.ashx?id=' + this.model.get("id");
这篇关于重定向响应下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!