【问题标题】:Uploading a file with filtering its extension上传带有过滤扩展名的文件
【发布时间】:2013-07-02 12:25:15
【问题描述】:

我有一个 ASP.Net Web 应用程序,我必须在其中上传文件:

@using (Html.BeginForm("Uploading_validation", "Super", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="dossier"  accept="*.iso, *.rar, *.zip"/>
   <br />
    @Html.Label("Date d'expiration")

    <input type="text" id="datepicker" name="duree" />
    <br />
 <input type="submit" value="OK" />
 }

我想只接受扩展名accept="*.iso, *.rar, *.zip",但它不起作用。

为什么这个过滤器不起作用?如何修改代码?

【问题讨论】:

    标签: c# .net asp.net-mvc file-upload razor


    【解决方案1】:

    您可以使用 FileExtensions 来实现:

    [Required, FileExtensions(Extensions=".iso,.rar,.zip", ErrorMessage="Incorrect file format")]
    

    将 Dossier 添加到您的模型以将其传递回视图并像这样呈现:

        @Html.TextBoxFor(m => m.Dossier, new { type = "file" })
        @Html.ValidationMessageFor(m => m.Dossier)
    

    它应该同时验证客户端和服务器端。

    【讨论】:

    • 我在一个项目中使用 MVC 4,无论我的扩​​展是否正确,这个解决方案都无效。终于通过this.解决了这个问题,希望能帮助像我这样卡在旧版本的人。
    【解决方案2】:

    accept 属性并非所有浏览器都支持。你不能依赖客户端,应该过滤文件。

    顺便说一句,你应该这样使用这个属性:

    accept="application/iso,application/rar,application/zip"
    

    更新:通过其他方式,您可以使用 javascript 验证文件扩展名:look at sample

    【讨论】:

    • 是的,我在动作中过滤了它,我需要在视图中
    • 似乎 crome 不支持这种正确 MIME 类型。此标记符合W3C spec
    【解决方案3】:

    这个sn-p似乎可以被所有浏览器接受

    @using (Html.BeginForm("Uploading_validation", "Super", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
    
        <input type="file" name="dossier"   accept=".rar , .zip"/>
       <br />
        @Html.Label("Date d'expiration")
    
        <input type="text" id="datepicker" name="duree" />
        <br />
     <input type="submit" value="OK" />
     }
    

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2010-12-31
      • 2019-06-19
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多