Display file size with two decimal points in PrimeFaces file upload component

221 Views Asked by At

We have a file upload functionality. Max file upload size is 3 mb and we are validating the file size in component level.

using sizeLimit="3000000" in p:fileUpload component

We are displaying error message like following

Maximum file size allowed to upload is 3 MB.: XXX.pdf 7.5 MB

But my requirement is display the file size with two decimal points like following

Maximum file size allowed to upload is 3 MB.: XXX.pdf 7.53 MB

Is it possible to do?

I tried with messageTemplate and jQuery but not able to do it.

1

There are 1 best solutions below

0
On

One solution is overriding the method for size calculation, within PrimeFaces js, using the prototype.

The code then should looks like:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:p="http://primefaces.org/ui"
    xmlns:c="http://java.sun.com/jstl/core">
<h:head>
</h:head>
<h:body>

    <script>
        PrimeFaces.widget.FileUpload.prototype.formatSize = function(a) {
            if (a === undefined) {
                return '';
            }
            if (a === 0) {
                return 'N/A';
            }
            var b = parseInt(Math.floor(Math.log(a) / Math.log(1024)));
            if (b === 0) {
                return a + ' ' + this.sizes[b];
            } else {
                return (a / Math.pow(1024, b)).toFixed(2) + ' ' + this.sizes[b];
            }
        };
    </script>


    <h:form id="frmClientDetails">
        <p:fileUpload value="#{fileUploadView.file}" mode="advanced"
            sizeLimit="100" invalidSizeMessage="Your error message" />
    </h:form>

</h:body>
</html>

Doing this you're setting two decimals(the only difference I add with PF 6.2 js), both in the error message and in the detail one.