ASP.NET MVC 3:DataAnnotations.FileExtensionsAttribute 不起作用 [英] ASP.NET MVC 3: DataAnnotations.FileExtensionsAttribute not working

查看:22
本文介绍了ASP.NET MVC 3:DataAnnotations.FileExtensionsAttribute 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 MSDN 文档,默认情况下 FileExtensionsAttribute (.NET 4.5) 应该只允许我上传 jpg、jpeg、gif 和 png 文件 - 这就是我想要的.

According to the MSDN documentation, by default the FileExtensionsAttribute (.NET 4.5) should allow me to only upload only jpg,jpeg,gif and png files - which is what I want.

我尝试上传没有该属性的 jpg,它有效.伟大的.然后我将该属性添加到我的视图模型中..

I tried uploading a jpg without the attribute, it works. Great. Then I added the attribute to my view model..

[FileExtensions(ErrorMessage = "Please specify a valid image file (.jpg, .jpeg, .gif or .png)")]
public HttpPostedFileBase ImageFile { get; set; }

没有快乐.验证失败并显示 ErrorMessage.最重要的是,似乎没有办法指定任何允许的自定义文件扩展名.我最终扩展了 FileExtensionsAttribute 并使用了我自己的验证逻辑,它按预期工作.但为什么这种方式行不通呢?

No joy. The verification fails and the ErrorMessage is shown. On top of that there doesn't seem to be a way to specify any allowed custom file extensions. I ended up extending the FileExtensionsAttribute and using my own verification logic, which works as expected. But why doesn't this way work?

将发布整个控制器并在需要时查看.我使用这个例子作为上传逻辑的基础,但使用 DataAnnotations.FileExtensionsAttribute 而不是 Microsoft.Web.Mvc.FileExtensions.. 如何在 ASP.NET MVC 中上传图片?

Will post the entire controller and view if required. I used this example as a basis for the uploading logic, but using the DataAnnotations.FileExtensionsAttribute instead of Microsoft.Web.Mvc.FileExtensions.. How do I upload images in ASP.NET MVC?

推荐答案

使用 Extensions 属性来设置它们.虽然根据文档

Use the Extensions property to set them. Although according to the documentation

文件扩展名,或默认文件扩展名(.png",.jpg"、.jpeg"和.gif")如果未设置该属性.

The file name extensions, or the default file extensions (".png", ".jpg", ".jpeg", and ".gif") if the property is not set.

您可以像设置 ErrorMessage 一样设置它.更可能的问题是它不知道如何评估 HttpPostedFileBase 是否具有正确的扩展名.您需要使用 MVC 框架中的框架或创建自己的框架.

You can set it just like you did the ErrorMessage. The more likely issue is that it doesn't know how to assess whether the HttpPostedFileBase has the right extension. You'll need to use the one from the MVC framework or create your own.

这篇关于ASP.NET MVC 3:DataAnnotations.FileExtensionsAttribute 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆