Home > OS >  ASP.NET Core Web API - How to validate file maximum upload size
ASP.NET Core Web API - How to validate file maximum upload size

Time:11-02

In ASP.NET Core-6 Web API application, I am trying to upload multiple files. I have this code

File Type Validation

public static bool CheckIfPdfFile(IFormFile file)
{
    var extension = "."   file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
    return (extension == ".pdf"); 
}

public class AdminFileModel
{
    public List<IFormFile> MyFile { get; set; }
}

Model:

public class MandateApprovalAttachment
{
    public Guid Id { get; set; }
    public string FileType { get; set; }
    public string FileName { get; set; }
    public string FilePath { get; set; }
    public long? FileSize { get; set; }
    public string MimeType { get; set; }
}

Then the main method that will perform the operation:

public async Task<Response<string>> MandateApproval(AdminFileModel model)
{
    var response = new Response<string>();
    string fileName = "";
    try
    {
            if (model.MyFile == null || model.MyFile.Count == 0)
            {
                response.Data = null;
                response.StatusCode = (int)HttpStatusCode.OK;
                response.Message = "No File Available for Upload";
                response.Successful = false;
                return await Task.FromResult(response);
            }
            foreach (var attachment in model.MyFile)
            {
                if (ConstantHelper.CheckIfPdfFile(attachment))
                {
                    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);
                    //attachment.CopyTo(fileStream);
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        await attachment.CopyToAsync(fileStream);
                    }
                    mandateAttachment.FileType = Path.GetExtension(attachment.FileName);
                    mandateAttachment.MimeType = attachment.ContentType;
                    mandateAttachment.FileName = fileName;
                    mandateAttachment.FilePath = filePath; 
                    await _unitOfWork.AdminMandateAttachments.InsertAsync(mandateAttachment);
                    await _unitOfWork.Save();
                }
                else
                {
                    response.Data = null;
                    response.StatusCode = (int)HttpStatusCode.OK;
                    response.Message = "Invalid File Extension! Kindly attach PDF File";
                    response.Successful = false;
                    return response;
                }
            }

            response.Message = "Successfully";
            transaction.Complete();
            response.StatusCode = (int)HttpStatusCode.OK;
            response.Successful = true;
            return response;
    catch (Exception ex)
    {
        response.Message = "An error occured";
        response.Successful = false;
        response.StatusCode = (int)HttpStatusCode.BadRequest;
        return response;
    }
}

I have validated that the FileType should be only PDF, and this is working.

But now, how do I validate that the Maximum FileSize should not excel exceed 5MB, and also save the FileSize into the DB?

Thanks

CodePudding user response:

There is an IFormFile.Length property, that will return the length of that file in bytes. (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.iformfile.length?view=aspnetcore-6.0)

So given, that attachment is an IFormFile, you can validate this by checking

attachment.Length <= 5 * 1024 * 1024
  • Related