【发布时间】:2018-03-25 05:25:05
【问题描述】:
我发现了一些类似Validate Image Type 的问题,但它并没有满足我的需求。
我有名为 Movie 的模型类,其中包含属性
public byte[] Image { get; set; }
我的视图包含
<form asp-action="Index" method="post" enctype="multipart/form-data">
<input asp-for="Image" type="file" id="files" class="form-control" />
<input type="submit" value="Create" class="btn btn-default" />
</form>
在控制器中,我将其转换为 bytes 并将其存储在数据库中。我想验证它,文件允许 .jpg、.jpeg、.png 和文件的最大大小 5Mb。
[HttpPost]
public async Task<IActionResult> Index(Movie Movie, List<IFormFile> Image)
{
foreach(var item in Image)
{
if (item.Length > 0)
{
using (var stream = new MemoryStream())
{
await item.CopyToAsync(stream);
Movie.Image = stream.ToArray();
}
}
}
_applicationDbContext.Movie.Add(Movie);
_applicationDbContext.SaveChanges();
return View();
}
如何验证上传的文件?
【问题讨论】:
-
请不要发布您的代码截图,而是发布代码本身
-
好的,我会编辑我的问题,感谢反馈
-
为什么不检查已知图像扩展名的文件名(带扩展名)??
-
为了检查大小,看看this..我的意思是你可以使用
FileInfo.Length并设置一个if条件,就是这样(注意length将返回文件大小(以字节为单位,您可能需要进行转换) -
在屏幕上显示?找回来?
标签: c# .net .net-core entity-framework-core image-upload