Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate file size and type in <p:fileUpload mode="simple">?

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?

like image 367
Abhishek Dhote Avatar asked Sep 30 '12 14:09

Abhishek Dhote


People also ask

What is P fileUpload?

The <p:fileUpload> component is used to create file upload button in JSF application.


1 Answers

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.
}
like image 158
BalusC Avatar answered Oct 23 '22 08:10

BalusC