In PrimeFaces 3.4, the <p:fileUpload>
attributes sizeLimit
and allowTypes
doesn't work in case of mode="simple"
. How can I validate the file size and allowable types?
The <p:fileUpload> component is used to create file upload button in JSF application.
The mode="simple"
generates a plain HTML5 <input type="file">
instead of using jQuery/Ajax file upload, so the client side facilities are limited.
If the webbrowser supports the new HTML5 File
API, then you could just make use of it. It adds support for the new accept
attribute on <input type="file">
and enables JavaScript to have access to specific file properties such as File#size
.
E.g.
<p:fileUpload mode="simple" styleClass="imagesOnlyMax10MB" />
with this JS (using jQuery from 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.
}
});
Otherwise, your best bet is really validating it in the server side. You could use ExternalContext#getMimeType()
to get a mime type based on file extension (you can manage all mime types as <mime-mapping>
in web.xml
; the container's own one has a bunch of default ones).
if (!externalContext.getMimeType(filename).startsWith("image/")) {
// Not an image.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With