ASP.NET Core Web API:验证文件最大上传大小并保存至数据库
实现文件大小验证并保存文件大小到数据库
针对你的需求,我们可以分步骤完成修改:
1. 添加文件大小验证方法
在你的ConstantHelper类中新增静态方法,用于验证文件是否不超过5MB(换算为字节是 5 * 1024 * 1024 = 5242880):
public static bool CheckFileSize(IFormFile file) { const long maxAllowedSize = 5 * 1024 * 1024; // 5MB return file.Length <= maxAllowedSize; }
2. 在上传逻辑中加入大小校验
修改MandateApproval方法的循环部分,在文件类型验证后添加大小检查,同时把文件大小存入数据库模型:
foreach (var attachment in model.MyFile) { // 验证文件类型 if (!ConstantHelper.CheckIfPdfFile(attachment)) { response.Data = null; response.StatusCode = (int)HttpStatusCode.BadRequest; response.Message = "Invalid File Extension! Kindly attach PDF File"; response.Successful = false; return response; } // 新增文件大小验证 if (!ConstantHelper.CheckFileSize(attachment)) { response.Data = null; response.StatusCode = (int)HttpStatusCode.BadRequest; response.Message = $"File {attachment.FileName} exceeds maximum allowed size (5MB)"; response.Successful = false; return response; } MandateApprovalAttachment mandateAttachment = new MandateApprovalAttachment(); string uploadFolder = Path.Combine(_iWebHostEnvironment.WebRootPath, "files/my_attachments"); fileName = Guid.NewGuid().ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + attachment.FileName; string filePath = Path.Combine(uploadFolder, fileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { await attachment.CopyToAsync(fileStream); } // 赋值文件大小到数据库字段 mandateAttachment.FileSize = attachment.Length; mandateAttachment.FileType = Path.GetExtension(attachment.FileName); mandateAttachment.MimeType = attachment.ContentType; mandateAttachment.FileName = fileName; mandateAttachment.FilePath = filePath; await _unitOfWork.AdminMandateAttachments.InsertAsync(mandateAttachment); await _unitOfWork.Save(); }
3. 配置ASP.NET Core请求大小限制
默认情况下ASP.NET Core会限制请求体大小,需在Program.cs中配置多部分表单的大小上限,避免文件还没到控制器就被拦截:
builder.Services.Configure<FormOptions>(options => { // 单文件最大限制设为5MB,多文件场景可按总需求放大,比如允许10个5MB文件则设为5242880 * 10 options.MultipartBodyLengthLimit = 5 * 1024 * 1024; });
额外优化建议
你的CheckIfPdfFile方法可以简化,避免多次分割文件名的冗余操作,同时兼容文件名无.的边界情况:
public static bool CheckIfPdfFile(IFormFile file) { var extension = Path.GetExtension(file.FileName).ToLowerInvariant(); return extension == ".pdf"; }
内容的提问来源于stack exchange,提问作者Ayobamilaye
相关产品推荐
相关产品推荐

