【问题标题】:How to restrict file upload to JPG, PNG, and GIF in ASP.NET MVC 3如何在 ASP.NET MVC 3 中将文件上传限制为 JPG、PNG 和 GIF
【发布时间】:2012-05-04 04:16:35
【问题描述】:

我在 HTML 表单中使用了一个简单的输入框 <input type="file" />,我想强制只能上传 JPG、PNG 和 GIF 文件。

我该怎么做?

【问题讨论】:

  • @Ahsan 我同意拉维的观点。但请注意,这只检查正在上传的文件的名称。文件的实际格式或内容仍然可以是任何内容。

标签: c# javascript jquery html asp.net-mvc-3


【解决方案1】:

您可以查看此链接,CodeProject: Image uploading

  $file = $("#yourFileuploadID");
                var $filePath = $.trim($file.val());
                if ($filePath == "") {
                    alert("Please browse a file to upload");
                    return;
                }

                var $ext = $filePath.split(".").pop().toLowerCase();
                var $allow = new Array("gif", "png", "jpg", "jpeg");
                if ($.inArray($ext, $allow) == -1) {
                    alert("Only image files are accepted, please browse a image file");
                    return;
                }

PS:最好有服务器端验证,当客户端禁用javascript时会很方便。确保同时检查两者

【讨论】:

  • Javascript 是不够的。您还必须检查网络服务器上的文件以验证 MIME 类型是否正确。
  • 就在那里。我们需要客户端和服务器验证
  • @Ravi 如果用户选择上传的文件包含 (".") 那么什么?
  • @Ahsan 检查“.”的最后一个实例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-22
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 2012-01-25
相关资源
最近更新 更多