假设 ASP.NET 和表单上传,有什么方法可以确保文件是图像?
有没有办法通过 MIME 类型或其他检查方式来判断文件是否是图像?这些图像将进入图库,我将根据需要调整它们的大小,并希望尽我所能确保我要使用 GDI 处理的文件实际上是一个图像。
Is there any way to tell if the file is an image either through MIME type or some other way of inspection? The images are going into a gallery and I'll be resizing them as necessary and want to ensure, to the best I can, that the file I'm about to process with GDI is, in fact, an image.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试将文件加载到 Bitmap 对象中。如果出现异常,那么它就不是图像。
Try to load the file into a Bitmap object. If if you get an exception then it isn't an image.
在 stackoverflow 上查看此问题/答案和这个。我相信这是一个重复的问题。
另外,请考虑读取文件的幻数,特别是如果您只是想确定文件是否是几种可接受的类型之一。 幻数维基百科
Check out this question/answer on stackoverflow and this one. I belive this is a duplicate question.
Also, look into reading a file's magic number especially if you are just trying to determine if the file is one of a few acceptable types. Magic number Wikipedia
是的,您可以检查 fileUploadCtrl.PostedFile.ContentType 属性,并将该字符串与预期的图像 MIME 类型列表(即 image/gif)进行比较。您还可以通过将上传的图像字节加载到 System.Drawing.Image 对象中来执行其他验证。如果它加载,您就知道您有一个好的图像,如果它加载失败,那么该图像可能是伪造的或未知的格式。
Yes, you can check the fileUploadCtrl.PostedFile.ContentType property and compare that string to an expected list of image MIME types i.e. image/gif. You can also perform additional validation by loading the uploaded image bytes into a System.Drawing.Image object. If it loads you know you have a good image, if it fails to load then perhaps the image is a forgery or an unknown format.