【问题标题】:Response object is not realising the file to Download in ASP.NET MVC framework响应对象没有实现在 ASP.NET MVC 框架中下载的文件
【发布时间】:2018-09-05 13:37:50
【问题描述】:

我正在尝试下载文件。 “似乎”一切正常,没有抛出异常。

我通过一个简单的 jQuery $.ajax 调用从前端调用动作控制器。

我的代码有什么问题?

MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("Line 1");
tw.WriteLine("Line 2");
tw.WriteLine("Line 3");
tw.Flush();
byte[] bytes = ms.ToArray();
ms.Close();

Response.Clear();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename= YourFileName.txt");
Response.BinaryWrite(bytes);
Response.End();

return Json(resultado, JsonRequestBehavior.AllowGet);

【问题讨论】:

  • 您将无法在同一个 HTTP 请求中返回 JSON 并下载文件。这不是 HTTP 的工作方式。如果您在 MVC 控制器中,请不要直接写入响应。而是返回一个包含文件数据的操作结果。

标签: c# jquery asp.net-mvc


【解决方案1】:

将您的代码更改为这个,它应该可以工作。

MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("Line 1");
tw.WriteLine("Line 2");
tw.WriteLine("Line 3");
tw.Flush();
byte[] bytes = ms.ToArray();
ms.Close();

return File(bytes, "text/plain", "YourFileName.txt");

如果在某些浏览器文本文件中自动打开而不是您可以尝试,“application/octet-stream”内容类型 hack.. 所以,最后一行应该是,

return File(bytes, "application/octet-stream", "YourFileName.txt");

【讨论】:

  • 如果 OP 像他们所说的那样进行 ajax 调用,这将不起作用。
【解决方案2】:

您应该知道的第一件事:您不能直接从 AJAX 回调返回文件,即使它使用 Response 实例。但是,您可以返回一个包含文件名的字符串,并将文件内容作为字节数组存储在 TempData 或 Session 中:

[HttpPost]
public ActionResult ActionName(...)
{
    byte[] bytes;

    // other logic here

    using (var ms = new MemoryStream())
    {
        TextWriter tw = new StreamWriter(ms);
        tw.WriteLine("Line 1");
        tw.WriteLine("Line 2");
        tw.WriteLine("Line 3");
        tw.Flush();
        bytes = ms.ToArray();
    }

    TempData["bytes"] = bytes; // add this line

    return Json(new { fileName = "YourFileName.txt" });
}

接下来,处理 AJAX 调用的 success 部分,将 window.location 或 window.location.href 设置为指向将下载文件的操作名称的 URL:

$.ajax({
    type: 'POST',
    url: '@Url.Action("ActionName", "ControllerName")',
    data: ...,
    success: function(result) {
        window.location = '@Url.Action("DownloadFile", "ControllerName")' + '?fileName=' + result.fileName; 
    }
});

最后,使用HTTP GET 方法创建一个控制器,并使用之前存储在TempData/Session 中的字节数组返回FileResult:

[HttpGet]
public FileResult DownloadFile(string fileName)
{
    if (TempData["bytes"] != null)
    {
        var content = TempData["bytes"] as byte[];
        return File(content, "application/octet-stream", fileName);
    }    
    else
    {
        return new EmptyResult();
    }
}

如果您以正确的方式执行所有这些操作,文本文件应该可以下载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多