在 PrimeFaces 3.4 中,<p:fileUpload>属性sizeLimit和allowTypes在mode="simple". 如何验证文件大小和允许的类型?
11498 次
1 回答
6
mode="simple"生成一个纯 HTML5 ,<input type="file">而不是使用 jQuery/Ajax 文件上传,因此客户端设施是有限的。
如果网络浏览器支持新的HTML5 FileAPI,那么您就可以使用它。它增加了对新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容器自己的有一堆默认类型)。
if (!externalContext.getMimeType(filename).startsWith("image/")) {
// Not an image.
}
于 2012-10-01T13:22:38.613 回答