You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PrimeFaces文件上传组件中显示两位小数的文件大小?

Solution for PrimeFaces FileUpload Error Message with Two Decimal Places

Client-Side Override

PrimeFaces uses a built-in client-side function to format file sizes in error messages. You can override this function to force two decimal places for all file upload widgets:

$(document).ready(function() {
    // Override PrimeFaces' default size formatting logic
    PrimeFaces.widget.FileUpload.prototype.formatSize = function(size) {
        const units = ['B', 'KB', 'MB', 'GB'];
        let unitIndex = 0;
        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }
        // Format to two decimal places and append unit
        return size.toFixed(2) + ' ' + units[unitIndex];
    };
});

Make sure this script loads after PrimeFaces' core JavaScript files (place it at the end of your page body or use the defer attribute). This will update all file upload error messages to show sizes with two decimal places.

Server-Side Custom Validator (Fallback)

If client-side changes don’t work for your setup, implement a server-side validator to fully control the error message:

  1. Create the custom validator class:
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.primefaces.model.UploadedFile;

@FacesValidator("customFileSizeValidator")
public class CustomFileSizeValidator implements Validator {

    private static final long MAX_UPLOAD_SIZE = 3 * 1024 * 1024; // 3MB

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        UploadedFile file = (UploadedFile) value;
        if (file != null && file.getSize() > MAX_UPLOAD_SIZE) {
            // Calculate and format file size to two decimals
            double fileSizeMB = file.getSize() / (1024.0 * 1024.0);
            String formattedSize = String.format("%.2f MB", fileSizeMB);
            String errorMessage = String.format("Maximum file size allowed to upload is 3 MB.: %s %s", file.getFileName(), formattedSize);
            
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, errorMessage));
        }
    }
}
  1. Update your p:fileUpload component to use this validator (you can keep sizeLimit for client-side checks, but the server-side validator will handle the message formatting):
<p:fileUpload validator="customFileSizeValidator" 
              mode="advanced" 
              <!-- other attributes --> />

This server-side approach acts as a safety net, ensuring correct formatting even if client-side validation is bypassed.

Notes

  • For PrimeFaces 10+, double-check the client-side function name in the source code if the override doesn’t work (rare, but possible with version updates).
  • When using the client-side override, test across browsers to ensure consistent behavior.

内容的提问来源于stack exchange,提问作者Kaushik Mitra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:20:24