我正在尝试创建一个zip归档文件并从我的Web API中返回它。该控制器从一个Angular 2网站调用。目前,zip文件已经被创建,但是当我打开它时,会出现无效的消息。最初,我在using语句中使用了流,但不得不更改,因为它们在请求完成之前就被销毁了。
我需要做的是创建zip文件,将csv文件添加到其内容中,然后返回zip文件。但是zip文件始终无效。我已经阅读过zip存档需要被释放才能写入其内容,但我不确定最佳实现方法是什么。非常感谢任何指导。
我需要做的是创建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);
}
}