Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading file from Azure blob storage via Memory Stream

I currently have an endpoint in my .net 7 API that when hit, should download a specific file from my blob storage by using the file name. When I test out the endpoint I get a 500 error stating "Time outs are not supported in this stream". I have attached the error below for more information.

Endpoint.cs

public IEndpointRouteBuilder MapEndpoints(IEndpointRouteBuilder endpoints)
{


    endpoints.MapGet("getBlob/{blobname}", async (string blobName, IApplicationFormService applicationFormService) => await applicationFormService.GetBlob(blobName))
        .Produces<FileStreamResult>();


    return endpoints;
}

Service.cs

public async Task<IResult> GetBlob(string blobName)
{

    BlobClient blobClient = _blobServiceClient
        .GetBlobContainerClient("root")
        .GetBlobClient(blobName);


    try
    {
        using (var memoryStream = new MemoryStream())
        {
            await blobClient.DownloadToAsync(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);


            var newMemoryStream = new MemoryStream(memoryStream.ToArray());


            return Results.Ok(new FileStreamResult(newMemoryStream, "application/octet-stream") { FileDownloadName = blobName });
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }



    return Results.Ok(blobName);
}

enter image description here

like image 292
svalaie Avatar asked Sep 03 '25 02:09

svalaie


1 Answers

The issue was that I was returning Results.ok() when I should have returned Results.File()

using (var memoryStream = new MemoryStream())
        {
            await blobClient.DownloadToAsync(memoryStream);
            //memoryStream.Seek(0, SeekOrigin.Begin);

            return Results.File(memoryStream.ToArray(), "application/octet-stream", blobName);
        }
like image 189
svalaie Avatar answered Sep 04 '25 16:09

svalaie