luni, 28 martie 2016

JSF 2.3 Multiple File Upload with HTML 5, AJAX and upload progress bar via web sockets


The source code from the above article was modified to support a progress bar via the JSF 2.3 web sockets. The main modifications implies:

- add <f:websocket/> in page

Note: In production, this web socket should be adjusted to distinguish between users there are login  (in case that you have this feature) via the optional user attribute (e.g. you can use: user="#{request.remoteUser}") - this is needed for sending messages to a single login user, the one who initiated the upload. In the form below, JSF will push messages to  to the current view only. You can also set scope="session" and push messages to all views in the current user session only. But we don't take into account if the user is login or not!

<f:websocket channel="upload" onmessage="socketListener" scope="view" />

Notice that this web socket it is automatically open when you start the application and it is not explictly closed. If you want to accomplish such features please read further JSF 2.3 - Explicitly open/close a websocket channel.

- provide a div where the upload progress is displayed (we display the percent as: x%), but you can choose to implement a visual progress bar:

<div id="progressBarId">0 %</div>

- provide the JavaScript listener for processing the incoming messages:

function socketListener(message, channel, event) {               
 document.getElementById("progressBarId").innerHTML = message + "%";
}

- on server-side, in UploadBean, you have to inject the PushContext via @Push annotation on the given channel name (upload):

@Inject
@Push(channel = "upload")
private PushContext push;

- and, finally, push the messages during upload:

push.send((totalReadSize * 100) / totalSize);

Below, you can see a possible output:


The complete application is available here.

Niciun comentariu:

Trimiteți un comentariu