54 lines
2.1 KiB
C#
54 lines
2.1 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using TakeoutSaaS.Application.Storage.Abstractions;
|
|
using TakeoutSaaS.Application.Storage.Contracts;
|
|
using TakeoutSaaS.Application.Storage.Extensions;
|
|
using TakeoutSaaS.Shared.Abstractions.Constants;
|
|
using TakeoutSaaS.Shared.Abstractions.Results;
|
|
using TakeoutSaaS.Shared.Web.Api;
|
|
|
|
namespace TakeoutSaaS.AdminApi.Controllers;
|
|
|
|
/// <summary>
|
|
/// 管理后台文件上传。
|
|
/// </summary>
|
|
[ApiVersion("1.0")]
|
|
[Authorize]
|
|
[Route("api/admin/v{version:apiVersion}/files")]
|
|
public sealed class FilesController(IFileStorageService fileStorageService) : BaseApiController
|
|
{
|
|
/// <summary>
|
|
/// 上传图片或文件。
|
|
/// </summary>
|
|
[HttpPost("upload")]
|
|
[RequestFormLimits(MultipartBodyLengthLimit = 30 * 1024 * 1024)]
|
|
[ProducesResponseType(typeof(ApiResponse<FileUploadResponse>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(ApiResponse<FileUploadResponse>), StatusCodes.Status400BadRequest)]
|
|
public async Task<ApiResponse<FileUploadResponse>> Upload([FromForm] IFormFile? file, [FromForm] string? type, CancellationToken cancellationToken)
|
|
{
|
|
// 1. 校验文件有效性
|
|
if (file == null || file.Length == 0)
|
|
{
|
|
return ApiResponse<FileUploadResponse>.Error(ErrorCodes.BadRequest, "文件不能为空");
|
|
}
|
|
|
|
// 2. 解析上传类型
|
|
if (!UploadFileTypeParser.TryParse(type, out var uploadType))
|
|
{
|
|
return ApiResponse<FileUploadResponse>.Error(ErrorCodes.BadRequest, "上传类型不合法");
|
|
}
|
|
|
|
// 3. 提取请求来源
|
|
var origin = Request.Headers["Origin"].FirstOrDefault() ?? Request.Headers["Referer"].FirstOrDefault();
|
|
await using var stream = file.OpenReadStream();
|
|
|
|
// 4. 调用存储服务执行上传
|
|
var result = await fileStorageService.UploadAsync(
|
|
new UploadFileRequest(uploadType, stream, file.FileName, file.ContentType ?? string.Empty, file.Length, origin),
|
|
cancellationToken);
|
|
|
|
// 5. 返回上传结果
|
|
return ApiResponse<FileUploadResponse>.Ok(result);
|
|
}
|
|
}
|