[英]415 (Unsupported Media Type) Error
On my MVC project, I have a POST request to a Web API using XmlHttpRequest
. 在我的MVC项目中,我使用
XmlHttpRequest
向Web API发送了POST请求。
I send an array of documents' routes in a JSON format and expecting to get from the server a Zip file (ArrayBuffer). 我以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");
}
And my ZipDocs function on the WebAPI (using the DotNetZip library): 还有我在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 };
}
But the response I'm getting from the server is: 但是我从服务器得到的响应是:
POST http://localhost:1234/MyProject/API/documents/zip 415 (Unsupported Media Type)
Why is this happening, and how do I fix it? 为什么会发生这种情况,我该如何解决?
Thanks to @David Duponchel I used the jquery.binarytransport.js library, I sent the data to the API as JSON and got back the Zip File as Binary. 感谢@David Duponchel,我使用了jquery.binarytransport.js库,将数据以JSON的形式发送到API,并以Zinary的形式返回了Zip文件。
This is my JavaScript ZipDocs function: 这是我的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");
}
});
}
The API's code remains the same. API的代码保持不变。
That works perfectly. 那很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.