Skip to content

Instantly share code, notes, and snippets.

@h09shais
Created February 23, 2021 17:27
Show Gist options
  • Save h09shais/abbc055d458e1d331f0e548218bd018c to your computer and use it in GitHub Desktop.
Save h09shais/abbc055d458e1d331f0e548218bd018c to your computer and use it in GitHub Desktop.
HttpResponseMessage download file and zip
private static HttpResponseMessage HttpReport(byte[] bytes, string fileName)
{
HttpResponseMessage httpResponseMessage;
using (var stream = new MemoryStream(bytes))
{
httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
httpResponseMessage.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
return httpResponseMessage;
}
private static HttpResponseMessage HttpZip(Dictionary<string, byte[]> reports)
{
HttpResponseMessage httpResponseMessage;
using (var stream = new MemoryStream())
{
using (var zipArchive = new ZipArchive(stream, ZipArchiveMode.Update, false))
{
foreach (var report in reports)
{
ZipArchiveEntry zipEntry = zipArchive.CreateEntry(report.Key);
using (var fileStream = new MemoryStream(report.Value))
{
using (Stream zipStream = zipEntry.Open())
{
fileStream.CopyTo(zipStream);
}
}
}
}
httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = $"Reports-{DateTime.UtcNow}.zip"
};
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
}
return httpResponseMessage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment