On my MVC project, I have a POST request to a Web API using XmlHttpRequest
.
I send an array of documents' routes in a JSON format and expecting to get from the server a Zip file (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):
[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?
Based on this post
You might want to try
xhr.setRequestHeader("Accept", "application/json");
And your code is missing a semicolon on
xhr.setRequestHeader("Content-type", "application/json")
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.
This is my JavaScript ZipDocs function:
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.
That works perfectly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.