【问题标题】:perform client side validation on file input - accept attribute doesn't work对文件输入执行客户端验证 - 接受属性不起作用
【发布时间】:2015-02-12 20:36:43
【问题描述】:

我目前正在尝试使用 C# 在 Visual Studio、ASP.net 中构建一个小型网站。 用户必须上传文件,但我只想接受 Excel 文件。

目前我已经有了这个服务器端验证:

public ActionResult Index(HttpPostedFileBase file){
  if (file != null && file.ContentLength > 0){
      string fileName = Path.GetFileName(file.FileName);
      if (fileName.EndsWith(".xlsx")) //enkel gewoon Excel bestand wordt aanvaard. {
           ...

这可以解决问题,但我不知道如何在客户端仅允许 Excel 文件。我目前有这个,但它还没有限制用户。我仍然可以上传任何我想要的文件。

<input type="file" name="file" value="Bestand kiezen" accept=".xlsx" /> 

我知道客户端限制并非 100% 万无一失,但我还是想实现该功能。提前致谢!

编辑:感谢下面的家伙,我得到了答案。我最终使用了这个,它显示了 .xls 和 .xlsx 文件

<input type="file" name="file" value="Bestand kiezen" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

【问题讨论】:

标签: c# html asp.net validation client-side


【解决方案1】:

&lt;input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" /&gt; 它应该工作

【讨论】:

    【解决方案2】:

    accept 属性被部分浏览器支持,但不是全部,支持程度不一;参见例如回复File input 'accept' attribute - is it useful?Input accept attribute in Firefox

    请注意,accept=".xlsx" 在支持的浏览器上限制输入文件扩展名为 .xlsx 的文件,因此通常会忽略使用旧版本 Excel 创建的 Excel 文件,这些文件会生成 .xls 文件。一般来说,任何可以处理.xlsx的软件都可以处理.xls

    【讨论】:

    • 嗯,那种工作,是的。弹出窗口仍然使用标准的 . 文件,但它也可以选择使用我指定的类型。谢谢顺便说一句!
    猜你喜欢
    • 2011-06-12
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多