Created
January 3, 2024 17:31
-
-
Save stogoh/9c038e6f79ed714de65bc83e0b931b9c to your computer and use it in GitHub Desktop.
ASP.NET Core In Memory File Download
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal static class DownloadEndpoint | |
{ | |
public static void MapDownloadEndpoints(this IEndpointRouteBuilder builder) | |
{ | |
builder | |
.MapGet("/api/download/{containerId}", DownloadContainer); | |
} | |
private static async Task DownloadContainer( | |
HttpContext context, | |
Guid containerId) | |
{ | |
context.Response.ContentType = "application/octet-stream"; | |
context.Response.Headers.Append("Content-Disposition", $"attachment; filename=\"Container-{containerId}.zip\""); | |
var folderPath = @$"D:\{containerId}"; | |
var files = Directory.GetFiles(folderPath); | |
var bodyStream = context.Response.BodyWriter.AsStream(); | |
using var archive = new ZipArchive(bodyStream, ZipArchiveMode.Create); | |
foreach (var file in files) | |
{ | |
var entry = archive.CreateEntry(Path.GetFileName(file), CompressionLevel.NoCompression); | |
var entryStream = entry.Open(); | |
var fileStream = File.OpenRead(file); | |
await fileStream.CopyToAsync(entryStream); | |
entryStream.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment