gpt4 book ai didi

c# - 在内存中创建 Zip 存档,并从 web api 返回它

转载 作者:行者123 更新时间:2023-11-30 19:53:06 28 4
gpt4 key购买 nike

所以我正在尝试创建一个 zip 存档并从我的 web api 返回它。从角度 2 站点调用 Controller 。目前已创建 zip 文件,但当我打开它时,我收到一条无效消息。最初我在 using 语句中有流,但不得不更改它,因为它们在请求完成之前被处理。

我需要的是创建 zip 文件,将 csv 文件添加到其内容中。然后返回 zip 文件。但是 zip 文件总是无效的。我已经阅读过需要处理 zip 存档以便写入其内容,但我不确定实现此目的的最佳方法是什么。感谢您的指导。

public async Task<IHttpActionResult> ExportReport(int id, ReportModel report)
{
try
{
var result = await ReportGenerationService.ExportReportForId(id, report.Page, report.PageSize, report.SortField, report.SortDir, report.SearchTerm, report.StartDate, report.EndDate, report.UserId, report.TeamId, report.SelectedDateItem);
if (result != null)
{

var compressedFileStream = new MemoryStream();

var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false);

var zipEntry = zipArchive.CreateEntry("textExport.csv");
var origionalFileSteam = new MemoryStream(result.ExportToBytes());
var zipEntryStream = zipEntry.Open();
origionalFileSteam.CopyTo(zipEntryStream);


var response = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StreamContent(compressedFileStream)};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Export.zip"
};

var t = compressedFileStream.CanRead;
return ResponseMessage(response);

}

return NotFound();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}

对 using 语句的响应:

有一次我将所有内容都包含在 using 语句中,但响应会失败,因为流已被释放。您可以在下面看到这一点。

public async Task<IHttpActionResult> ExportReport(int id, ReportModel report)
{
try
{
var result = await ReportGenerationService.ExportReportForId(id, report.Page, report.PageSize, report.SortField, report.SortDir, report.SearchTerm, report.StartDate, report.EndDate, report.UserId, report.TeamId, report.SelectedDateItem);
if (result != null)
{

var compressedFileStream = new MemoryStream();
var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false);

//Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry("textExport.csv");

//Get the stream of the attachment
using (var originalFileStream = new MemoryStream(result.ExportToBytes()))
using (var zipEntryStream = zipEntry.Open()) {
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);
}
compressedFileStream.Position = 0;

var response = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StreamContent(compressedFileStream)};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Export.zip"
};

return ResponseMessage(response);
}

return NotFound();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}

最佳答案

您缺少一些 using(){} block 。

确保以正确的顺序关闭 originalFileSteam、zipEntryStream 和 zipArchive。

为了确定,重置内存流。我不知道是否需要这样做,但不会有什么坏处。

//using (var compressedFileStream = new MemoryStream())
var compressedFileStream = new MemoryStream();

using (var zipArchive = new ZipArchive(...))
{
//Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry("textExport.csv");

//Get the stream of the attachment
using (var originalFileStream = new MemoryStream(result.ExportToBytes()))
using (var zipEntryStream = zipEntry.Open())
{
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);
}
}

//compressedFileStream .Position = 0;
var responseBytes =new MemoryStream(compressedFileStream.ToArray());

var response = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StreamContent(responseBytes )};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

return ResponseMessage(response);

关于c# - 在内存中创建 Zip 存档,并从 web api 返回它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50720298/

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