Files
Yi.Framework/Yi.Abp.Net8/module/rbac/Yi.Framework.Rbac.Application/Services/FileService.cs
chenchun 94834f45c3 perf: 使用 FileStreamResult 流式返回文件,避免一次性读取到内存
改为 FileStream 并返回 FileStreamResult,减小内存占用并支持大型文件;修正变量名拼写并添加 null-forgiving 标记。
2025-11-06 11:13:50 +08:00

70 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;
using Yi.Framework.Core.Enums;
using Yi.Framework.Core.Helper;
using Yi.Framework.Rbac.Application.Contracts.Dtos.FileManager;
using Yi.Framework.Rbac.Application.Contracts.IServices;
using Yi.Framework.Rbac.Domain.Entities;
using Yi.Framework.Rbac.Domain.Managers;
namespace Yi.Framework.Rbac.Application.Services
{
public class FileService : ApplicationService, IFileService
{
private readonly IRepository<FileAggregateRoot> _repository;
private readonly FileManager _fileManager;
public FileService(IRepository<FileAggregateRoot> repository, FileManager fileManager)
{
_repository = repository;
_fileManager = fileManager;
}
/// <summary>
/// 下载文件,支持缩略图
/// </summary>
/// <returns></returns>
[Route("file/{code}/{isThumbnail?}")]
public async Task<IActionResult> Get([FromRoute] Guid code, [FromRoute] bool? isThumbnail)
{
var file = await _repository.GetAsync(x => x.Id == code);
var path = file?.GetQueryFileSavePath(isThumbnail);
if (path is null || !File.Exists(path))
{
return new NotFoundResult();
}
var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
return new FileStreamResult(stream, file!.GetMimeMapping());
}
/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
public async Task<List<FileGetListOutputDto>> Post([FromForm] IFormFileCollection file)
{
var entities = await _fileManager.CreateAsync(file);
for (int i = 0; i < file.Count; i++)
{
var entity= entities[i];
using (var steam = file[i].OpenReadStream())
{
await _fileManager.SaveFileAsync(entity,steam);
}
}
return entities.Adapt<List<FileGetListOutputDto>>();
}
}
}