簡體   English   中英

415(不支持的媒體類型)錯誤

[英]415 (Unsupported Media Type) Error

在我的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");
}

還有我在WebAPI上的ZipDocs函數(使用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) 

為什么會發生這種情況,我該如何解決?

根據這篇文章

您可能要嘗試

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

而且您的代碼缺少分號

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

感謝@David Duponchel,我使用了jquery.binarytransport.js庫,將數據以JSON的形式發送到API,並以Zinary的形式返回了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的代碼保持不變。

那很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM