【问题标题】:What should I return from my .NET controller to AngularJS when downloading a file?下载文件时,我应该从我的 .NET 控制器返回什么到 AngularJS?
【发布时间】:2016-07-04 14:21:44
【问题描述】:

我正在尝试下载一个仅包含一个极长的逗号分隔字符串的 CSV 模板。我的 API 端点是这样的:

public HttpResponse DownloadTemplate()
{
    var attachment = "attachment; filename=template.csv";
    var headers = "Header1,Header2,Header3,HeaderAndSoOnAndSoForth";

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.AddHeader("Content-Disposition", attachment);
    HttpContext.Current.Response.ContentType = "text/csv";
    HttpContext.Current.Response.AddHeader("Pragma", "public");
    HttpContext.Current.Response.Write(headers);

    return HttpContext.Current.Response;
}

这是由一个简单的 AngularJS $http.post 请求调用的:

$http.post('api/Files/DownloadTemplate').success(function (data) {
    // Do something with data.
});

但是,当我检查网络响应时,似乎根本没有返回任何内容。我做错了什么?

(有朋友建议把文件存到服务器里直接下载。由于种种原因,我不能这样做。)

【问题讨论】:

标签: .net angularjs asp.net-mvc


【解决方案1】:

我有点想知道为什么您不只是返回字符串,因为您正在立即处理 $http.post 中的数据。所以也许这个答案不适用,但我还是会发布它,因为我花了一段时间才弄清楚它是否相关,那就太好了。

但是,如果我们谈论的是真正的文件下载,我已经在 Angular 中实现它,调用我的 WebAPI,使用以下技术:

public HttpResponseMessage DownloadFile()
{
    var content = DoSomeProcessingToGetContentAsByteArray();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        // Haven't checked, but there may be a StringContent() instead?
        Content = new ByteArrayContent(content)
    };

    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "template.csv"
    };

    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    return result;
}

然后来自 Angular:

window.open("http://whatever/api/Files/DownloadTemplate", "_blank", "");

会提示用户保存文件。

【讨论】:

  • 让我检查一下并回复您。目前正在移动,所以我还不能完全测试它。
猜你喜欢
  • 2014-08-19
  • 2021-07-14
  • 1970-01-01
  • 2015-07-19
  • 1970-01-01
  • 2015-07-29
  • 2010-11-20
  • 2016-06-18
  • 2015-12-23
相关资源
最近更新 更多