← Back to Files
FileView.cshtml.cs
using KaiChat.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace KaiChat.Pages;
public class FileViewModel : PageModel
{
private readonly IFileService _file;
public FileViewModel(IFileService file)
{
_file = file;
}
public string FileName { get; set; } = "";
public string CurrentFolder { get; set; } = "";
public string FileContent { get; set; } = "";
public string FileSize { get; set; } = "";
public DateTime LastModified { get; set; }
public IActionResult OnGet(string? path)
{
if (string.IsNullOrEmpty(path))
return RedirectToPage("Files");
var relativePath = path.TrimStart('/');
FileName = Path.GetFileName(relativePath);
CurrentFolder = Path.GetDirectoryName(relativePath)?.Replace('\\', '/') ?? "";
var fullPath = Path.Combine(
HttpContext.RequestServices.GetRequiredService<IConfiguration>().GetValue<string>("KaiChat:BaseFolder")!,
relativePath);
if (!System.IO.File.Exists(fullPath))
return NotFound();
var fileInfo = new FileInfo(fullPath);
FileSize = FormatSize(fileInfo.Length);
LastModified = fileInfo.LastWriteTime;
FileContent = _file.ReadFile(relativePath);
return Page();
}
private static string FormatSize(long bytes) => bytes switch
{
< 1024 => $"{bytes} B",
< 1024 * 1024 => $"{bytes / 1024.0:F1} KB",
< 1024 * 1024 * 1024 => $"{bytes / (1024.0 * 1024):F1} MB",
_ => $"{bytes / (1024.0 * 1024 * 1024):F1} GB"
};
}