415(不支持的媒体类型)错误

时间:2016-05-13 07:40:27

标签: javascript c# asp.net-web-api xmlhttprequest zip

在我的MVC项目中,我使用XmlHttpRequest对Web API发出POST请求。

我以JSON格式发送一组文档路径,并希望从服务器获取一个Zip文件(ArrayBuffer)。

self.zipDocs = function (docs, callback) {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {//Call a function when the state changes.
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseBody);
        }
    }
    xhr.open("POST", '../API/documents/zip', true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.responseType = "arraybuffer";
    console.log(docs);
    xhr.send(docs);

    var arraybuffer = xhr.response;
    var blob = new Blob([arraybuffer], { type: "application/zip" });
    saveAs(blob, "example.zip");
}

我的ZipDocs在WebAPI上运行(使用DotNetZip库):

[HttpPost]
    [Route("documents/zip")]
    public HttpResponseMessage ZipDocs([FromBody] string[] docs)
    {

    using (var zipFile = new ZipFile())
    {
        zipFile.AddFiles(docs, false, "");
        return ZipContentResult(zipFile);
    }
}

protected HttpResponseMessage ZipContentResult(ZipFile zipFile)
{
    // inspired from http://stackoverflow.com/a/16171977/92756
    var pushStreamContent = new PushStreamContent((stream, content, context) =>
    {
       zipFile.Save(stream);
        stream.Close(); // After save we close the stream to signal that we are done writing.
    }, "application/zip");

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

但我从服务器得到的回复是:

POST http://localhost:1234/MyProject/API/documents/zip 415 (Unsupported Media Type)

为什么会发生这种情况,我该如何解决?

2 个答案:

答案 0 :(得分:3)

基于this post

您可能想尝试

xhr.setRequestHeader("Accept", "application/json");

您的代码缺少分号

xhr.setRequestHeader("Content-type", "application/json")

答案 1 :(得分:1)

感谢@David Duponchel我使用了jquery.binarytransport.js库,我将数据作为JSON发送到API,并将Zip文件作为二进制文件返回。

这是我的JavaScript ZipDocs功能:

self.zipDocs = function (docs, callback) {
    $.ajax({
        url: "../API/documents/zip",
        type: "POST",
        contentType: "application/json",
        dataType: "binary",
        data: docs,
        processData: false,
        success: function (blob) {
            saveAs(blob, "ZippedDocuments.zip");
            callback("Success");
        },
        error: function (data) {
            callback("Error");
        }
    });
}

API的代码保持不变。

完美无缺。