我的要求是使用 Web API 通过网络发送一个 zip 文件(依次由一堆文件组成),它不应该写在本地任何地方(不应该写在服务器/客户端磁盘上的任何地方)。对于压缩,我
在服务器上使用 DotNetZip - Ionic.Zip.dll 代码:
public async Task<IHttpActionResult> GenerateZip(Dictionary<string, StringBuilder> fileList)
{
// fileList is actually a dictionary of “FileName”,”FileContent”
byte[] data;
using (ZipFile zip = new ZipFile())
{
foreach (var item in filelist.ToArray())
{
zip.AddEntry(item.Key, item.Value.ToString());
}
using (MemoryStream ms = new MemoryStream())
{
zip.Save(ms);
data = ms.ToArray();
}
}
var result = new HttpResponseMessage(HttpStatusCode.OK);
MemoryStream streams = new MemoryStream(data);
//, 0, data.Length-1, true, false);
streams.Position = 0;
//Encoding UTFEncode = new UTF8Encoding();
//string res = UTFEncode.GetString(data);
//result.Content = new StringContent(res, Encoding.UTF8, "application/zip");
<result.Content = new StreamContent(streams);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
//result.Content.Headers.ContentLength = data.Length;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "test.zip";
return this.Ok(result);
}
我面临的问题是,在客户端下载的 zip 文件修改为 test.bin 后,其流内容(本示例内容中的字节 [] 数据)丢失。(我正在取回一个 test.zip 文件。当我在本地将文件从 test.zip 更改为 test.bin 时,我看到文件的内容如下所示。它不包含 Response.Content 值。PS 我有还尝试了 MIME 类型“application/octet-stream”。没有运气!)
Test.zip aka test.bin 的内容:
{“version”:{“major”:1,“minor”:1,“build”: -1,"revision":-1,"majorRevision":-1,"minorRevision":-1},
"content":{"headers":[{"key":"Content-Type","value": [“应用程序/zip”]},
{“密钥”:
"statusCode":200,"reasonPhrase":"OK","headers":[],"isSuccessStatusCode":true}
有人可以帮助我了解如何使用 MemoryStream 对象设置 result.Content(我在 google 的其他地方看到了“FileStream”示例来设置“result.Content”,但我只想使用 MemoryStream 对象!)。我之所以强调这一点,是因为我认为问题在于将 MemoryStream 对象设置为 result.Content (为了将流内容正确保存到 result.Content 对象中)
PS我也已经通过AngularJS 上传/下载字节数组和ASP.NET Web API(和一堆其他链接),但它对我没有多大帮助...... :( 非常感谢任何帮助。非常感谢提前:)