Time for action – using the FileUpload component
Let us see how we can use the FileUpload component to upload the user profile image of type .jpg
, .jpeg
, .gif
, or .png
, which should be a maximum of 1 MB:
- Create a user account form to upload the user image:
<h:form enctype="multipart/form-data"> <p:fileUpload fileUploadListener="#{userController.handleUserPicUpload}" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" invalidFileMessage="Only gif, jpg or png type images are allowed" sizeLimit="1048576" invalidSizeMessage="File size should not exceed 1MB"/> </h:form>
- Implement the
actionListener
method to save the uploaded image:public void handleUserPicUpload(FileUploadEvent event) { UploadedFile uploadedFile = event.getFile(); String fileName = uploadedFile.getFileName(); byte[] contents = uploadedFile.getContents(); //logic to save byte[] FacesMessage msg = new FacesMessage("...