【问题标题】:Redirect response to download file重定向下载文件的响应
【发布时间】:2012-05-24 03:49:10
【问题描述】:

我有一个通用处理程序,我使用这个非常基本的 js 代码调用它:

    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);

我的通用处理程序代码看起来不错。基本上我正在尝试构建响应头,我认为当这个处理程序返回时,它会开始下载文件。

处理程序代码:

   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 请求正常完成。这是我返回的响应标头:

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

我错过了什么?我做错了什么?

【问题讨论】:

  • 有什么问题?文件没有被放入响应中吗?
  • @sinni800 刚回来,没下载。

标签: c# javascript xmlhttprequest


【解决方案1】:

这不会在浏览器中开始下载。使用 POST 请求很难实现。如果您只传递一个 id,它不能是一个 GET 请求吗?然后你就做

document.location.href = '/genericHandlers/DownloadFile.ashx?id=' + this.model.get("id");

【讨论】:

  • 这很好用。谢谢你。你能看出在这种情况下使用GET 而不是POST 有什么缺点吗?
  • 我想缺点是我无法进行任何错误处理,例如文件不存在。
  • @MikeFielden 您可以 - 如果文件不存在,只需提供错误页面或重定向,而不是提供下载。当然,这意味着离开页面。也许在你给你的用户点击链接之前检查你的文件是否存在。
猜你喜欢
  • 2021-02-19
  • 2021-09-17
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多