I have a project, .NET Core 7 for the backend and NextJs for the frontend. Based on user’s need and requirements, there are many files (as videos with .mp4 format) in my windows VPS saved inside a folder with their unique name. When user clicks on download using their device, these videos start downloading automatically. Right now, almost everything works fine in terms of downloading video. There is a small problem that I have no idea where it is coming from. I want when a user clicks on download, the download dialog of the browser shows the file that is being downloaded. Right now, the way it works is first it downloads completely, after completion informs the user that your file is downloaded completely.
I was searching for the similar problem, I figured out that I have to add “Content-Disposition” header with “attachment” and my file name. Even though I added that to my header, still it downloads, then it shows the completed dialog.
Down below is my code:
Code for my service:
public async Task<Stream?> GetVideoStreamAsync(string videoCode, CancellationToken cancellationToken = default)
{
var localVideoPath = Path.Combine(BaseVideoPath, videoCode + ".mp4");
if (File.Exists(localVideoPath))
{
await using var fs = new FileStream(localVideoPath, FileMode.Open, FileAccess.Read, FileShare.Read);
var sr = new MemoryStream();
await fs.CopyToAsync(sr, cancellationToken);
sr.Position = 0; // Reset the position of the MemoryStream to the start after copying
return sr;
}
return null;
}
And here is my controllers code:
[HttpGet("GetStream")]
public async Task<IActionResult> StreamVideo([FromQuery] string videoCode, CancellationToken cancellationToken = default)
{
try
{
var filePath = Path.Combine(BaseVideoPath, videoCode + ".mp4");
if (!System.IO.File.Exists(filePath))
{
return NotFound("Video not found.");
}
var fileInfo = new FileInfo(filePath);
var fileLength = fileInfo.Length;
var videoStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var fileName = $"{videoCode}.mp4";
Response.ContentType = "video/mp4";
Response.Headers.Add("Content-Disposition", $"attachment; filename="{fileName}"");
Response.Headers.Add("Accept-Ranges", "bytes");
if (Request.Headers.ContainsKey("Range"))
{
return await ProcessRangeRequest(videoStream, fileLength, cancellationToken);
}
// Set the Content-Length for full downloads
Response.ContentLength = fileLength;
return File(videoStream, "video/mp4", enableRangeProcessing: true);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to stream video");
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
private async Task<IActionResult> ProcessRangeRequest(Stream videoStream, long actualFileSize, CancellationToken cancellationToken)
{
var rangeHeader = RangeHeaderValue.Parse(Request.Headers["Range"].ToString());
var range = rangeHeader.Ranges.First();
var start = range.From ?? 0;
var end = range.To ?? actualFileSize - 1;
if (start >= actualFileSize || end >= actualFileSize)
{
Response.Headers.Add("Content-Range", $"bytes */{actualFileSize}");
return StatusCode(StatusCodes.Status416RequestedRangeNotSatisfiable);
}
var contentLength = end - start + 1;
Response.StatusCode = StatusCodes.Status206PartialContent;
Response.Headers.Add("Content-Range", $"bytes {start}-{end}/{actualFileSize}");
Response.ContentLength = contentLength;
// Position the stream and copy the range to the response body
videoStream.Position = start;
await videoStream.CopyToAsync(Response.Body, Convert.ToInt32(end - start + 1), cancellationToken);
return new EmptyResult();
}
Has anyone had the same issue before ? I would appreciate if you can help me solve this problem. Thanks
I have tried almost every header, changing the “Content-Disposition” but still, the same problem.