c# - 如何在 ASP.Net Core 中验证上传的文件
问题描述
我正在使用 ASP.NET Core 2.2,并且正在使用模型绑定来上传文件。
这是我的用户视图模型
public class UserViewModel
{
[Required(ErrorMessage = "Please select a file.")]
[DataType(DataType.Upload)]
public IFormFile Photo { get; set; }
}
这是我的视图
@model UserViewModel
<form method="post"
asp-action="UploadPhoto"
asp-controller="TestFileUpload"
enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="Photo" />
<span asp-validation-for="Photo" class="text-danger"></span>
<input type="submit" value="Upload"/>
</form>
最后这是MyController
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UploadPhoto(UserViewModel userViewModel)
{
if (ModelState.IsValid)
{
var formFile = userViewModel.Photo;
if (formFile == null || formFile.Length == 0)
{
ModelState.AddModelError("", "Uploaded file is empty or null.");
return View(viewName: "Index");
}
var uploadsRootFolder = Path.Combine(_environment.WebRootPath, "uploads");
if (!Directory.Exists(uploadsRootFolder))
{
Directory.CreateDirectory(uploadsRootFolder);
}
var filePath = Path.Combine(uploadsRootFolder, formFile.FileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(fileStream).ConfigureAwait(false);
}
RedirectToAction("Index");
}
return View(viewName: "Index");
}
如何使用 .jpeg 和 .png 等特定扩展名将上传的文件限制在 5MB 以下?我认为这两个验证都是在 ViewModel 中完成的。但我不知道该怎么做。
解决方案
您可以自定义验证属性MaxFileSizeAttribute
,如下所示
最大文件大小属性
public class MaxFileSizeAttribute : ValidationAttribute
{
private readonly int _maxFileSize;
public MaxFileSizeAttribute(int maxFileSize)
{
_maxFileSize = maxFileSize;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var file = value as IFormFile;
if (file != null)
{
if (file.Length > _maxFileSize)
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"Maximum allowed file size is { _maxFileSize} bytes.";
}
}
AllowedExtensionsAttribute
public class AllowedExtensionsAttribute : ValidationAttribute
{
private readonly string[] _extensions;
public AllowedExtensionsAttribute(string[] extensions)
{
_extensions = extensions;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var file = value as IFormFile;
if (file != null)
{
var extension = Path.GetExtension(file.FileName);
if (!_extensions.Contains(extension.ToLower()))
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"This photo extension is not allowed!";
}
}
将MaxFileSize
属性和AllowedExtensions
属性添加到Photo
属性
public class UserViewModel
{
[Required(ErrorMessage = "Please select a file.")]
[DataType(DataType.Upload)]
[MaxFileSize(5* 1024 * 1024)]
[AllowedExtensions(new string[] { ".jpg", ".png" })]
public IFormFile Photo { get; set; }
}
推荐阅读
- laravel - Laravel DomPDF 使用 Axios 时获取空白文件
- puppeteer - Puppeteer 使用 addScriptTag 添加 jQuery:“此文档需要 'TrustedScript' 分配”
- c++ - 在Qt中按下按钮时在小部件内显示带有动画的小部件
- python - Live Plotting in PyQt5 GUI
- java - JTable disappears when implementing TableModelListener
- mongoose - Remove Result Type for Mongoose Nestjs Promises
- c - 我如何编写 C 编程大写字母分隔函数?
- python-3.x - 需要帮助将 Unix 时间戳解码为日期(不和谐)
- arrays - 有限的字符串在 C 中接受无限的字符
- amazon-web-services - 如何从消息 ID 调试 AWS SNS 的传递状态?