?-6ren"> ?-在 PrimeFaces 3.4 中,属性 sizeLimit和allowTypes在 mode="simple" 的情况下不起作用。如何验证文件大小和允许的类型? 最佳答案 mode="simple-6ren">
gpt4 book ai didi

file-upload - 如何验证文件大小和类型

?

转载 作者:行者123 更新时间:2023-12-02 17:29:50 25 4
gpt4 key购买 nike

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

最佳答案

mode="simple"生成纯 HTML5 <input type="file">而不是使用 jQuery/Ajax 文件上传,因此客户端设施受到限制。

如果网络浏览器支持新的HTML5 File API ,那么你就可以利用它了。它增加了对新 accept 的支持属性 <input type="file">并使 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 类型(您可以将所有 mime 类型管理为 <mime-mapping> 中的 web.xml ;容器自己的 mime 类型有一堆默认类型)。

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

关于file-upload - 如何验证文件大小和类型 <p :fileUpload mode ="simple">?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12661967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com