验证ASP.Net Core中IFormFile的图像类型 [英] Validate Image type for IFormFile in ASP.Net Core
问题描述
我有一个ASP.NET Core应用程序,我需要验证上传的文件是图像,而不是具有图像扩展名的非图像文件.... 我发现并有意义的所有解决方案都使用System.Drawing.Image或ASP.NET Core中不可用的类似类. 您能推荐一个替代方法吗? *请注意,我并不是要检查扩展名,而是要检查其内容.
I have an ASP.NET Core application and I need to validate that the uploaded file is an image and not a non-image file which has an image extension.... All solutions that I found and makes sense use System.Drawing.Image or similar classes that aren't available in ASP.NET Core. Can you kindly suggest an alternative? *Please note that I'm not trying to check the extension but the contents.
谢谢
推荐答案
现在,.System.Drawing.Common" NuGet可用于.NET Core.
Now "System.Drawing.Common" NuGet is available for .NET Core.
您可以执行以下操作来验证可能"的图像:
You can do the following to validate the "possible" images:
using System.Drawing;
// ...
public bool IsImage(byte[] data)
{
var dataIsImage = false;
using (var imageReadStream = new MemoryStream(data))
{
try
{
using (var possibleImage = Image.FromStream(imageReadStream))
{
}
dataIsImage = true;
}
// Here you'd figure specific exception to catch. Do not leave like that.
catch
{
dataIsImage = false;
}
}
return dataIsImage;
}
这篇关于验证ASP.Net Core中IFormFile的图像类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!