在PrimeFaces 3.4中,<p:fileUpload>
属性sizeLimit
和allowTypes
在mode="simple"
的情况下不起作用。如何验证文件大小和允许的类型?
mode="simple"
生成一个普通的HTML5 <input type="file">
,而不是使用jQuery/Ajax文件上传,因此客户端功能有限。
如果网络浏览器支持新的HTML5 File
API,那么你就可以使用它。它增加了对<input type="file">
上新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 类型<mime-mapping>
;容器自己的容器有一堆默认类型)。
if (!externalContext.getMimeType(filename).startsWith("image/")) {
// Not an image.
}