第九章:文件上传与数据统计

博客v1.0系列教程(Csharp)博客 v1.0 系列教程 (C#)

9.1 文件上传

支持本地存储和七牛云两种模式:

public class UploadService : IUploadService
{
    private readonly IConfiguration _config;

    public async Task<UploadResult> UploadAsync(IFormFile file)
    {
        var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.Name)}";
        var savePath = Path.Combine("uploads", fileName);

        // 保存到本地
        using var stream = File.Create(savePath);
        await file.CopyToAsync(stream);

        // 同步到七牛云(可选)
        if (_config.GetValue<bool>("QiNiu:Enabled"))
        {
            await SyncToQiNiuAsync(savePath, fileName);
        }

        return new UploadResult
        {
            Url = $"/uploads/{fileName}",
            FileName = fileName,
            Size = file.Length
        };
    }

    private async Task SyncToQiNiuAsync(string filePath, string fileName)
    {
        var accessKey = _config["QiNiu:AccessKey"];
        var secretKey = _config["QiNiu:SecretKey"];
        var bucket = _config["QiNiu:Bucket"];

        var mac = new Mac(accessKey, secretKey);
        var uploadManager = new UploadManager();

        await uploadManager.UploadFileAsync(filePath, fileName,
            new UploadSettings { Bucket = bucket });
    }
}

9.2 数据统计

public class DataService : IDataService
{
    public async Task<DashboardDto> GetDashboardAsync()
    {
        return new DashboardDto
        {
            ArticleCount = await _articleRepo.AsQueryable().CountAsync(),
            UserCount = await _userRepo.AsQueryable().CountAsync(),
            CommentCount = await _commentRepo.AsQueryable().CountAsync(),
            TodayViews = await GetTodayViewsAsync(),
            ArticleGrowth = await GetMonthlyGrowthAsync()
        };
    }

    private async Task<List<GrowthDto>> GetMonthlyGrowthAsync()
    {
        return await _articleRepo.AsQueryable()
            .GroupBy(a => a.CreateTime.Value.Month)
            .Select(g => new GrowthDto
            {
                Month = g.Key,
                Count = g.Count()
            })
            .ToListAsync();
    }
}

9.3 统计端点

app.MapGet("/api/data/sum", async (IDataService service) =>
{
    var dashboard = await service.GetDashboardAsync();
    return Results.Ok(dashboard);
});

app.MapGet("/api/data/article/year", async (IDataService service) =>
{
    var growth = await service.GetArticleGrowthAsync();
    return Results.Ok(growth);
});

下一章将实现日志系统与项目部署。

csharpuploadstatisticsdashboard