Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions LearningHub.Nhs.WebUI/Controllers/Api/ResourceController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@ namespace LearningHub.Nhs.WebUI.Controllers.Api
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using LearningHub.Nhs.Models.Enums;
using LearningHub.Nhs.Models.Resource;
using LearningHub.Nhs.Models.Resource.Activity;
using LearningHub.Nhs.Models.Resource.Contribute;
using LearningHub.Nhs.WebUI.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

Expand Down Expand Up @@ -60,6 +65,7 @@ public async Task<ActionResult> AcceptSensitiveContentAsync(int resourceVersionI
/// <param name="fileName">File name.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
[HttpGet("DownloadResource")]
[AllowAnonymous]
public async Task<IActionResult> DownloadResource(string filePath, string fileName)
{
if (string.IsNullOrEmpty(fileName))
Expand All @@ -70,7 +76,15 @@ public async Task<IActionResult> DownloadResource(string filePath, string fileNa
var file = await this.fileService.DownloadFileAsync(filePath, fileName);
if (file != null)
{
return this.File(file.Content, file.ContentType, fileName);
// Set response headers.
this.Response.ContentType = file.ContentType;
this.Response.ContentLength = file.ContentLength;
var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = fileName };
this.Response.Headers["Content-Disposition"] = contentDisposition.ToString();

// Stream the file in chunks with periodic flushes to keep the connection active.
await this.StreamFileWithKeepAliveAsync(file.Content, this.Response.Body, this.HttpContext.RequestAborted);
return this.Ok();
}
else
{
Expand Down Expand Up @@ -105,7 +119,16 @@ public async Task<IActionResult> DownloadResourceAndRecordActivity(int resourceV
ActivityStatus = ActivityStatusEnum.Completed,
};
await this.activityService.CreateResourceActivityAsync(activity);
return this.File(file.Content, file.ContentType, fileName);

// Set response headers.
this.Response.ContentType = file.ContentType;
this.Response.ContentLength = file.ContentLength;
var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = fileName };
this.Response.Headers["Content-Disposition"] = contentDisposition.ToString();

// Stream the file in chunks with periodic flushes to keep the connection active.
await this.StreamFileWithKeepAliveAsync(file.Content, this.Response.Body, this.HttpContext.RequestAborted);
return this.Ok();
}
else
{
Expand Down Expand Up @@ -584,5 +607,20 @@ public async Task<List<string>> GetObsoleteResourceFile(int resourceVersionId, b
var result = await this.resourceService.GetObsoleteResourceFile(resourceVersionId, deletedResource);
return result;
}

/// <summary>
/// Reads from the source stream in chunks and writes to the destination stream,
/// flushing after each chunk to help keep the connection active.
/// </summary>
private async Task StreamFileWithKeepAliveAsync(Stream source, Stream destination, CancellationToken cancellationToken)
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken)) > 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken);
await destination.FlushAsync(cancellationToken);
}
}
}
}
35 changes: 26 additions & 9 deletions LearningHub.Nhs.WebUI/Services/FileService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,23 +135,40 @@
{
var file = directory.GetFileClient(fileName);

if (await file.ExistsAsync())
var properties = await file.GetPropertiesAsync();
long fileSize = properties.Value.ContentLength;

try
{
if (fileSize <= 900 * 1024 * 1024)
{
return await file.DownloadAsync();
// For smaller files, download the entire file as a stream.
var response = await file.DownloadAsync();
return new FileDownloadResponse
{
Content = response.Value.Content,
ContentType = properties.Value.ContentType,
ContentLength = fileSize,
};
}
}
else if (await sourceDirectory.ExistsAsync())
{
var file = sourceDirectory.GetFileClient(fileName);

if (await file.ExistsAsync())
else
{
return await file.DownloadAsync();
// For large files, open a read stream
return new FileDownloadResponse
{
Content = await file.OpenReadAsync(),
ContentType = properties.Value.ContentType,
ContentLength = fileSize,
};
}
}
catch (Exception ex)
{
throw new Exception($"Error downloading file: {ex.Message}");
}

return null;
}

Check failure on line 171 in LearningHub.Nhs.WebUI/Services/FileService.cs

View workflow job for this annotation

GitHub Actions / Build and test

} expected

Check failure on line 171 in LearningHub.Nhs.WebUI/Services/FileService.cs

View workflow job for this annotation

GitHub Actions / Build and test

} expected

/// <summary>
/// The StreamFileAsync.
Expand Down
Loading