How to check file size and type in <p: fileUpload mode = "simple">?
1 answer
mode="simple"generates simple HTML5 <input type="file">instead of using jQuery / Ajax file upload, so client-side tools are limited.
If your web browser supports the new HTML5 FileAPI , you can simply use it. It adds support for the new attribute acceptin <input type="file">and allows JavaScript to access certain file properties, such as File#size.
eg.
<p:fileUpload mode="simple" styleClass="imagesOnlyMax10MB" />
JS ( jQuery PrimeFaces):
$("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.
}
+6