How to Upload Files With PrimeFaces and JSF Safely
Upload files in JSF with PrimeFaces p:fileUpload: size and type limits, UploadedFile, safe storage outside the web root and common errors.

Uploads combine two risks: large bodies that eat memory, and files that an attacker chooses the name and content of. PrimeFaces makes the mechanics easy, and safety is your code. This uses PrimeFaces 14, Jakarta Faces 4 and JDK 25. The general risk is in path traversal.
The component
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{uploadBean.handle}"
mode="advanced" dragDropSupport="true"
sizeLimit="5242880" allowTypes="/(\.|\/)(gif|jpe?g|png|pdf)$/"
multiple="false" auto="true" update="messages"/>
<p:messages id="messages" showDetail="true"/>
</h:form>mode="advanced" uses AJAX with a progress bar and drag and drop. mode="simple" is a plain multipart form post that works with p:commandButton ajax="false". The sizeLimit is in bytes (5 MB here). The allowTypes regular expression is matched against the file name on the client.
The listener
@Named
@RequestScoped
public class UploadBean {
private static final Path ROOT = Path.of("/var/app/uploads");
private static final Set<String> TYPES = Set.of("image/png", "image/jpeg", "image/gif", "application/pdf");
public void handle(FileUploadEvent event) throws IOException {
UploadedFile file = event.getFile();
if (file.getSize() > 5 * 1024 * 1024) throw new ValidatorException(msg("File too large"));
if (!TYPES.contains(sniff(file))) throw new ValidatorException(msg("Unsupported type"));
String stored = UUID.randomUUID() + extensionFor(sniff(file));
try (InputStream in = file.getInputStream()) {
Files.copy(in, ROOT.resolve(stored), StandardCopyOption.REPLACE_EXISTING);
}
attachments.save(new Attachment(stored, file.getFileName(), file.getSize()));
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Uploaded " + file.getFileName()));
}
}The rules this follows:
Check on the server. The sizeLimit and allowTypes attributes run in the browser. Anyone can bypass them with a custom request. The server enforces size, type and count again.
Do not trust the content type or name. Both are supplied by the client. Detect the type from the first bytes ("magic numbers") with a library such as Apache Tika, or at least compare the extension to the sniffed type. A file called photo.png may contain a script or an HTML page.
Never build the path from the supplied name. A name like ../../../etc/cron.d/job writes outside your directory. Generate a random name, as with UUID above, keep the original name in the database for display, and escape it wherever it is shown.
Store outside the web root. Files saved under the deployed application directory may be served and executed. Keep them in a separate directory or object storage, and serve through an endpoint that sets the content type and Content-Disposition.
Server limits
The request must get through the container before your code runs. Set limits in the right places:
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>native</param-value>
</context-param>
<multipart-config>
<max-file-size>5242880</max-file-size>
<max-request-size>10485760</max-request-size>
</multipart-config>With the native uploader the servlet container's multipart settings apply, and an oversized upload is cut off there. A reverse proxy has its own limit, for example client_max_body_size in nginx, and an upload failing with a 413 before reaching the application is that limit.
Large files and malware
Stream to disk rather than reading the whole file into memory, as above, so a few large uploads cannot exhaust the heap. For files that other users will download, scan with an antivirus service and mark the file as unavailable until scanned.
Common errors
A listener that never fires is usually a missing enctype="multipart/form-data" on the form, or an h:form with prependId confusion. A silent failure on large files is the container limit. Issues with partial updates after upload follow the rules in AJAX updates, and the form basics are in JSF validation and messages.
Never trust the name or the type the browser sends
An uploaded file arrives with a file name and a content type, and the user chose both. A script can send shell.jsp labelled image/png, or a name such as ../../etc/passwd. Two small checks remove most of the risk: look at the first bytes of the content to find out what the file really is, and reduce the name to a safe string before it touches the file system. This program does both and prints the results, on Eclipse Temurin.
static String sniff(byte[] head) {
if (head.length >= 8 && (head[0] & 0xFF) == 0x89 && head[1] == 'P' && head[2] == 'N' && head[3] == 'G') return "image/png";
if (head.length >= 3 && (head[0] & 0xFF) == 0xFF && (head[1] & 0xFF) == 0xD8 && (head[2] & 0xFF) == 0xFF) return "image/jpeg";
if (head.length >= 5 && new String(head, 0, 5).equals("%PDF-")) return "application/pdf";
return "unknown";
}
static String safeName(String submitted) {
String base = Path.of(submitted.replace('\\', '/')).getFileName().toString();
return base.replaceAll("[^A-Za-z0-9._-]", "_");
}real png bytes, claimed image/png : sniffed image/png
php source renamed shell.png : sniffed unknown
report.pdf -> report.pdf
../../etc/passwd -> passwd
C:\Users\x\evil.jsp -> evil.jsp
photo (1).png -> photo__1_.png
..hidden -> ..hiddenThe signature check accepted genuine PNG bytes and rejected a PHP script renamed to shell.png, whatever the browser claimed. The name function turned both path traversal attempts into plain file names by taking only the last path segment, after normalising Windows separators, and replaced awkward characters. The last row shows its gap: a name that starts with dots survives. Strip leading dots as well, and better still, do not use the submitted name for storage at all. Generate your own identifier, keep the original name as metadata for display, and store the file outside the web root so that nothing uploaded can be requested and executed as a page.
String storedName = UUID.randomUUID() + extensionFor(sniffedType); // .png, .pdf
Path target = uploadRoot.resolve(storedName).normalize();
if (!target.startsWith(uploadRoot)) throw new SecurityException("path escape");
Files.copy(file.getInputStream(), target);Wire the component with the limits on the page and on the server
The PrimeFaces component can restrict types and size in the browser, which improves the user experience and does not protect the server. Repeat every limit in the listener, because a request can bypass the page.
<p:fileUpload mode="advanced" auto="true"
listener="#{uploadBean.handle}"
allowTypes="/(\.|\/)(png|jpe?g|pdf)$/"
sizeLimit="5242880"
update="messages" />public void handle(FileUploadEvent event) throws IOException {
UploadedFile file = event.getFile();
if (file.getSize() > MAX_BYTES) throw new IllegalArgumentException("file too large");
byte[] head = file.getInputStream().readNBytes(16);
String type = sniff(head);
if (!ALLOWED.contains(type)) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsupported file type", null));
return;
}
store(file, type);
}The container has limits of its own, and the smaller one wins. In a Servlet 3 container the multipart-config in web.xml sets max-file-size and max-request-size; Tomcat's maxPostSize and a proxy's client_max_body_size (nginx) apply before your code. A 413 response from the proxy never reaches JSF, so the symptom is an upload that fails with no message from the application. Set the same number at every layer and write it down.
Scan and isolate what you keep
A valid PNG can still carry a payload for a vulnerable image library, and a PDF can contain scripts. For files that other users download, scan them with an antivirus service on arrival and quarantine until the result is clean. Re-encode images (read, resize and write again) so that metadata and appended data are discarded. Serve downloads with Content-Disposition: attachment and X-Content-Type-Options: nosniff, so a browser never runs an uploaded file as a page. Keep the upload directory out of the application server's deployment, owned by a user that cannot execute files there, and limit how much a single user can store, or the disk becomes a denial of service.
Test the upload path like an attacker would
The checks above only count if something exercises them. A small set of tests with hostile input proves they hold. Send a file whose bytes are text but whose name and content type say image, a name with a path traversal, a file at exactly the limit and one byte over it, and an empty file. Each should end in a clean rejection with a message the user can read, and none should leave a file behind.
@Test
void rejectsAScriptDisguisedAsAnImage() throws Exception {
UploadedFile fake = fakeUpload("shell.png", "image/png", "<?php echo 1; ?>".getBytes());
bean.handle(new FileUploadEvent(new UIComponentBase() { public String getFamily() { return "x"; } }, fake));
assertThat(uploadRoot).isEmptyDirectory();
}Run the same cases against the deployed application with curl -F '[email protected];type=image/png', because a proxy or a filter can change the behaviour between your test and production.
Where this does not apply
For very large uploads, a direct to object storage presigned URL avoids passing the data through the application. Documentation: the PrimeFaces FileUpload page and the OWASP file upload cheat sheet.


