Using Primefaces FileUpload to insert images to Primefaces Editor.

Primefaces Editor provides a way of adding an Image to a text using a image path (URL) . However, it does not provide an out of the box solution for uploading images to the server and adding the image to the text. We will illustrate a way of combining Primefaces editor with Primefaces FileUpload to solve this issue.

First we construct our XHTML file with a editor and a file uplaod widget.

We added a FileUpload widget directly after the editor widget. We gave the editor the id “editor”.

We will need this in the backing bean:

The method is a basic uploadListener for storing the uploaded file on the server (in /var/webapp/uploads ). The important part happens in lines 45-49 where we insert the image in to the text of the editor. Primefaces adds a textarea called editor_input where the actual text is entered (_input is appended to the id we set in the xhtml file). So what we do here is append an img tag to the text in edit_input and the force the client component to update (line 49). This appends the image to the end of the text, so one has to position it manually after the upload, but the editor supports dragging elements so that is no big deal. In my example I point the img url to /rais/uploads , this is the configured in my web.xml for static files which should not be updated or removed when I redeploy the application.

The web.xml:

I’m sure there are ways of improving this method. So if you find better ways post them in the comments.

Tagged with: , , , , , ,
5 comments on “Using Primefaces FileUpload to insert images to Primefaces Editor.
  1. Dave says:

    Please help provide the referenced class related to “FilenameUtils” and “setText”

    • admin says:

      Hi Dave,
      I added the missing information. Basically the setText is the setter method for the text value to which the editor binds (value=”#AnnouncementBean.text}”), and FilenameUtils is from org.apache.commons.io
      Hope this helped.

  2. Tadas says:

    Hi,

    In xhtml I have form id=”form” and I can’t make to work your code… I use PF 5.3 and I get error: “Cannot find component for expression “editor_input” referenced from “j_id1”. Of corse I tryed to write: form:editor_input

    also what observed – after upload and browser refresh image appear in editor

  3. testo blends says:

    Hi there, I enjoy reading all of your article post. I wanted to write a little comment
    to support you.

  4. vcor says:

    Hey! Do you know if they make ɑny plugins to safeguard ɑgainst hackers?
    I’m kinda paranoid аbout losing everything I’ve woгked harԀ οn. Any tips?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

seven + 8 =

*