【问题标题】:AJAX POST does not return a file downloadAJAX POST 不返回文件下载
【发布时间】:2015-09-01 00:59:21
【问题描述】:

我的 ASP.NET MVC 应用程序中有一个 POST AJAX 请求,其工作方式如下:

$.ajax({
    type: "POST",
    url: 'https://localhost:44300/api/values',
    data: ruleData,
    contentType: "application/json; charset=utf-8"
});

在这种情况下,ruleData 包含一个 JSON blob:

var ruleData = JSON.stringify({
    'TargetProduct': "SomeProduct",
    'Content': editor.getValue(),
    'TargetProductVersion' : "1.0"
});

请求由 Web API 应用程序中处理的 POST 支持,该应用程序返回带有适当标头的 PushStreamContent

return new HttpResponseMessage(HttpStatusCode.OK) { Content = pushStreamContent};

在 Fiddler 中,我看到来自 Web API 的响应返回为 application/octet-stream,大小符合我的预期(它在后端生成一个 ZIP 文件),但是从来没有显示允许用户下载文件。

我错过了什么?

【问题讨论】:

  • 你的控制器里有没有像stackoverflow.com/questions/730699/…这样的东西
  • 问题是 - 我使用的是ApiController,它与 MVC 控制器的规则不同,也不会暴露 File 可返回。

标签: ajax asp.net-mvc post asp.net-web-api


【解决方案1】:

用 XHR 解决

var xhr = new XMLHttpRequest();
                xhr.responseType = "blob";
                xhr.onreadystatechange = function(){
                    if (this.readyState == 4) {
                        if (this.status == 200)
                            {
                            download(xhr.response, "bundle.zip", "application/zip");
                        }
                        else if (this.status == 400) {
                            var reader = new FileReader();
                            reader.onload = function(e) {
                                var text = reader.result;
                                alert(text);
                            }
                            reader.readAsText(xhr.response);
                        }
                    }
                }
                xhr.open('POST', 'https://localhost:44300/api/values');
                xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
                xhr.responseType = 'blob'; // the response will be a blob and not text
                xhr.send(ruleData); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多