我正在使用 ASP.NET Core MVC。我需要 的数据注释/自定义数据注释IFormFile,检查所选/上传的文件是图像,图像的扩展名必须匹配*.png,*.jpg或*.jpeg。这是视图模型
public class ProductViewModel
{
[Display(Name = "Image")]
[Required(ErrorMessage = "Pick an Image")]
//[CheckIfItsAnImage(ErrorMessage = "The file selected/uploaded is not an image")]
public IFormFile File { get; set; }
}
Run Code Online (Sandbox Code Playgroud) 如何使用文件路径获取 IFormFile 实例?在本例中,该文件是存储在文件夹中的图像wwwroot。
我将向您提供一些我想要实现的目标的背景信息:
我想更新产品,因此为了做到这一点,我必须在视图上显示产品信息,包括它的文件名旁边的<input type="file" class="form-control-file" asp-for="File">. 所以用户知道,它已经有一个图像,当然我在执行 HTTP Post 请求时不会有问题,因为没有选择文件(如果用户不想更新图像)。问题是产品类没有 IFormFile 属性,它只有图像名称,而视图模型负责拥有 IForm 文件。那么,在将 ProductViewModel 作为参数发送到视图之前,如何将图像名称或路径转换为 IFormFile 呢?
这是我的视图、视图模型和我的产品类别:
Update.cshtml
<form enctype="multipart/form-data" method="post" asp-controller="Product" asp-action="Update">
<div class="form-group">
<label asp-for="Name"></label>
<input type="text" class="form-control" asp-for="Name" placeholder="Cereal, Ice cream, Tuna, etc...">
<span class="text-danger" asp-validation-for="Name"></span>
</div>
<div class="form-group">
<label asp-for="File"></label>
<input type="file" class="form-control-file" asp-for="File">
</div>
<button class="btn btn-success">Save Changes</button>
</form>
Run Code Online (Sandbox Code Playgroud)
ProductViewModel.cshtml
public class ProductViewModel
{
public string Name { get; set; }
public IFormFile File { get; …Run Code Online (Sandbox Code Playgroud)