gpt4 book ai didi

c# - 在 asp.net web api 中使用 MemoryStream 和 ZipArchive 将 zip 文件返回给客户端

转载 作者:太空狗 更新时间:2023-10-29 20:58:23 25 4
gpt4 key购买 nike

我正在尝试使用以下代码将 zip 文件从 asp.net web api 返回到客户端:

private byte[] CreateZip(string data)
{
using (var ms = new MemoryStream())
{
using (var ar = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
var file = archive.CreateEntry("file.html");

using (var entryStream = file.Open())
using (var sw = new StreamWriter(entryStream))
{
sw .Write(value);
}
}
return memoryStream.ToArray();
}
}

public HttpResponseMessage Post([FromBody] string data)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(CreateZip(data));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip, application/octet-stream");
return result;
}

当我运行这段代码时,出现以下错误:

ExceptionMessage":"The format of value 'application/zip, application/octet-stream' is invalid."

这是JS代码:

$.ajax({
type: "POST",
url: url,
data: data,
dataType: application/x-www-form-urlencoded
});

有什么解释为什么会这样吗?我真的很感谢你们的帮助

最佳答案

$.ajax 处理文本响应并将尝试 (utf-8) 解码内容:您的 zip 文件不是文本,您将得到损坏的内容。 jQuery 不支持二进制内容,因此您需要使用 this链接并在 jQuery 上添加 ajax 传输或直接使用 XmlHttpRequest。对于 xhr,您需要设置 xhr.responseType = "blob" 并从 xhr.response 中读取 blob。

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

// with xhr.responseType = "blob"
var blob = xhr.response;
saveAs(blob, "example.zip");
Edit: examples:

jquery.binarytransport.js (任何允许您下载 Blob 或 ArrayBuffer 的库都可以)

$.ajax({
url: url,
type: "POST",
contentType: "application/json",
dataType: "binary", // to use the binary transport
// responseType:'blob', this is the default
data: data,
processData: false,
success: function (blob) {
// the result is a blob, we can trigger the download directly
saveAs(blob, "example.zip");
}
// [...]
});

使用原始 XMLHttpRequest,您可以看到 this问题,你只需要添加一个 xhr.responseType = "blob" 来获得一个 blob。

我个人推荐你在 jQuery 上使用 ajax 传输,这很简单,你必须下载一个库,将它包含在项目中并写:dataType: "binary".

这是 API 代码,使用 DotNetZip (Ionic.Zip):

   [HttpPost]
public HttpResponseMessage ZipDocs([FromBody] string[] docs)
{
using (ZipFile zip = new ZipFile())
{
//this code takes an array of documents' paths and Zip them
zip.AddFiles(docs, false, "");
return ZipContentResult(zip);
}
}

protected HttpResponseMessage ZipContentResult(ZipFile zipFile)
{
var pushStreamContent = new PushStreamContent((stream, content, context) =>
{
zipFile.Save(stream);
stream.Close();
}, "application/zip");

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

关于c# - 在 asp.net web api 中使用 MemoryStream 和 ZipArchive 将 zip 文件返回给客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37530252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com