Using DWR to develop Ajax-based file upload portlet

Source: Internet
Author: User
Tags file upload progress bar exo platform

Introduction

The Web portal provides a central gateway for users to access various resources and services. At the same time, they also provide users with a platform to share resources with other users. From photos to audio and video files to scientific datasets used for research, users can share any content. Therefore, file upload is a basic feature of a Web portal.


Today's Web portals rely heavily on Java portlet technology. Although many Ajax developers have provided various File Upload progress bar solutions, we have not heard of any portlet-based solution. This document describes how to develop an Ajax-based file upload portlet that displays the progress bar of the file upload process. This portlet is especially useful for those who want to share large audio, video, and scientific files.


To keep up with the progress of this article, you should be familiar with Web development using Java Servlets and JavaServer Pages (JSPs. In addition, you must understand the development of portal and portlet technologies. Of course, if you are not very familiar with the portlet technology, do not give up this article now, because you will see a brief introduction to the portlet technology in this article, and some useful resources can be used to help you speed up the learning process.


Before testing the File Upload portlet provided in this article, consider using a portal framework that complies with the JSR 168 specifications, such as IBM & reg; WebSphere & reg; portal Server, Apache Pluto, eXo platform, or Liferay Portal. We use Apache Pluto 1.0.1, JDK 5.0 Update 10, and Apache Ant Version 1.6.5 In this article.


Basic concepts of portlet


Generally, A portlet can be considered as a Web component. The Portlet is similar to servlet, but the former focuses more on the presentation layer of applications. The typical output of A portlet is an HTML clip, which can be assembled by a Web portal. The Portlet itself is managed by the portlet container. The main features of the portlet include:


Multi-Mode: the portlet can have different views in different modes. For example, in addition to the view mode, the portlet also supports the edit mode so that users can set their own preferences.

Multiple window statuses: the portlet can be minimized and maximized.

Customizable parameters: the portlet can define parameters, which can be customized by the user.

For more details about the portlet, refer to Java Portlet Specification 1.0 and JSR 168 (JSR 168 is expected to be released in the next half year of JSR 286, it includes some improvements, such as inter-portlet communication and portlet filter ). For more information, see references.


Start creating File Upload portlet


The cornerstone of the file upload portlet is the Apache Commons FileUpload package (also called FileUpload in this article ). In addition to servlet File uploads, the Apache Commons FileUpload Version 1.1 package also supports File Uploads in the portlet. This article uses Apache Commons FileUpload version 1.2.


Basically, the upload progress bar of the Development file takes two steps:


Retrieving files from the server

Search and display client files from the Portal Server


Server-side retrieval during File Upload


The FileUpload package allows you to use a listener to retrieve the File Upload process. The doUpload () method (uk. ac. dl. esc. gtg. myportlets. fileupload. fileUploadPortlet, including the source files provided in the download section of this article), set the process listener for PortletFileUpload by calling the setProgressListener () method, as shown in Listing 1:

 

Listing 1. Set a process listener for the file upload package


DiskFileItemFactory factory = new DiskFileItemFactory ();
PortletFileUpload pfu = new PortletFileUpload (factory );
Pfu. setSizeMax (uploadMaxSize); // Maximum upload size
Pfu. setProgressListener (new FileUploadProgressListener ());
 


The listener FileUploadProgressListener (see Listing 2) can implement the org. apache. commons. fileupload. ProgressListener interface. The update () method is automatically called by the FileUpload package to refresh the latest information about the number of transmitted bytes. In this article, the progress is updated every 10 KB of data transferred. This helps prevent frequent updates. The getFileUploadStatus () method is used to calculate the upload progress of the current file. It can be called by the client through DWR (discussed in the next section ).


Listing 2. retrieving the File Upload listener during File Upload

 

Package uk. ac. dl. esc. gtg. myportlets. fileupload;

Import java. text. NumberFormat;

Import org. apache. commons. fileupload. ProgressListener;
Import org. apache. commons. logging. Log;
Import org. apache. commons. logging. LogFactory;

Public class FileUploadProgressListener implements ProgressListener {
Private static Log log = LogFactory. getLog (FileUploadProgressListener. class );

Private static long bytesTransferred = 0;

Private static long fileSize =-100;

Private long tenKBRead =-1;

Public FileUploadProgressListener (){
}

Public String getFileUploadStatus (){
// Per looks like 0%-100%, remove % before submission
String per = NumberFormat. getPercentInstance (). format (
(Double) bytesTransferred/(double) fileSize );
Return per. substring (0, per. length ()-1 );
}

Public void update (long bytesRead, long contentLength, int items ){
// Update bytesTransferred and fileSize (if required) every 10 KB is
// Read
Long tenKB = bytesRead/10240;
If (tenKBRead = tenKB)
Return;
TenKBRead = tenKB;

BytesTransferred = bytesRead;
If (fileSize! = ContentLength)
FileSize = contentLength;
}

}
 


Client retrieval during File Upload


The communication between the server and the client over the file upload process is implemented through Ajax. We use Direct Web Remoting (DWR) to provide Ajax support in the portlet. DWR is an ideal framework for Java developers. It can be used to introduce Ajax into Web development because it allows JavaScript in the browser to interact with Java objects on the server. To use dwr in a portlet, follow these steps (for more information about how to configure DWR, see references ):


The beauty of Direct Web Remoting is that the client can interact with Java objects on the server.


Configure DwrServlet through WEB-INF/web. xml (see listing 3 ).

Define one or more server-side objects with which clients can communicate in the WEB-INF/dwr. xml. In Listing 4, FileUploadProgressListener defines DWR so that the client can call this automatically generated JavaScript. In addition, only the getFileUploadStatus method can be called by the client, and the other public method update is not allowed to be accessed (see Listing 2 ).

Include the JavaScript code related to dwr in the fileupload-view.jsp (see listing 5 ).

Include the DWR library in the portlet application.


Listing 3. configuring DwrServlet in the WEB-INF/web. xml

 

<! -- DWR servlet -->
<Servlet>
<Servlet-name> dwr-invoker </servlet-name>
<Display-name> DWR Servlet </display-name>
<Servlet-class> org. directwebremoting. servlet. DwrServlet </servlet-class>
<Init-param>
<Param-name> debug </param-name>
<Param-value> false </param-value>
</Init-param>
</Servlet>

<! -- DWR servlet mapping -->
<Servlet-mapping>
<Servlet-name> dwr-invoker </servlet-name>
<Url-pattern>/dwr/* </url-patter>
</Servlet-mappin>
 


Listing 4. WEB-INF/dwr. xml

 

<! DOCTYPE dwr PUBLIC "-// GetAhead Limited // DTD Direct Web Remoting 2.0 // EN"
Http://getahead.org/dwr//dwr20.dtd>

<Dwr>
<Allow>
<Create creator = "new" javascript = "FileUploadProgressListener">
<Param name = "class"
Value = "uk. ac. dl. esc. gtg. myportlets. fileupload. FileUploadProgressListener"/>
<Include method = "getFileUploadStatus"/>
</Create>
</Allow>
</Dwr>
 


The JSP file fileupload-view.jsp shown in listing 5 shows how DWR helps retrieve the File Upload process from the server. Once the file is selected and the Upload button is clicked (see figure 1), The fileupload_ajax_query_upload_status () method is called immediately. This method then calls the getFileUploadStatus () method of FileUploadProgressListener in asynchronous mode (see Listing 2 ). The beauty of DWR is that the client can interact with the Java object on the server. Once a response is received, the fileupload_ajax_show_upload_status () method is called to refresh the process. If the file upload is incomplete, the update process will be retrieved after two seconds.


Listing 5. File Upload portlet JSP file-fileupload-view.jsp

 

<% @ Page session = "false" %>
<% @ Page contentType = "text/html" %>
<% @ Page import = "javax. portlet. PortletURL" %>
<% @ Taglib uri = "http://java.sun.com/portlet" prefix = "portlet" %>
<Portlet: defineObjects/>

<Script type = "text/javascript"
Src = <% = renderResponse. encodeURL (renderRequest. getContextPath ()
+ "/Dwr/interface/FileUploadProgressListener. js") %>
</SC

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.