【发布时间】:2016-09-09 07:13:21
【问题描述】:
在我的 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)
为什么会发生这种情况,我该如何解决?
【问题讨论】:
标签: javascript c# asp.net-web-api xmlhttprequest zip