【问题标题】:How to validate file size and type in <p:fileUpload mode="simple">?如何在 <p:fileUpload mode="simple"> 中验证文件大小和类型?
【发布时间】:2023-03-03 08:22:24
【问题描述】:

在 PrimeFaces 3.4 中,&lt;p:fileUpload&gt; 属性 sizeLimitallowTypesmode="simple" 的情况下不起作用。如何验证文件大小和允许的类型?

【问题讨论】:

  • 任何限制自己使用简单模式的理由。 This 可能会帮助您了解您是否正在寻找客户端解决方案,因为简单模式使用本机浏览器上传,没有任何限制。
  • 我使用简单模式有两个原因:(a)我只是限制要上传的文件数量为 ONE 和(b)我希望在点击表单提交时上传文件按钮。

标签: file-upload jsf-2 primefaces


【解决方案1】:

mode="simple" 生成一个纯 HTML5 的&lt;input type="file"&gt;,而不是使用 jQuery/Ajax 文件上传,因此客户端设施有限。

如果网络浏览器支持新的HTML5 File API,那么您可以直接使用它。它增加了对&lt;input type="file"&gt; 上新的accept 属性的支持,并使JavaScript 能够访问特定的文件属性,例如File#size

例如

<p:fileUpload mode="simple" styleClass="imagesOnlyMax10MB" />

使用这个 JS(使用 PrimeFaces 中的 jQuery):

$("input[type=file].imagesOnlyMax10MB").attr("accept", "image/*").on("change", function() {
    var max = 10 * 1024 * 1024; // 10MB

    if (this.files && this.files[0].size > max) {
        alert("File too large."); // Do your thing to handle the error.
        this.value = null; // Clears the field.
    }
});

否则,您最好的选择是在服务器端验证它。您可以使用ExternalContext#getMimeType() 来获取基于文件扩展名的mime 类型(您可以在web.xml 中将所有mime 类型管理为&lt;mime-mapping&gt;;容器自己的有一堆默认类型)。

if (!externalContext.getMimeType(filename).startsWith("image/")) {
    // Not an image.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    相关资源
    最近更新 更多