Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

Developing web services, Part 3: File uploading web service built with Apache CFX

Kuntal Ganguly (, Jr. Developer, Protech Infosystems Pvt. Ltd
Kuntal Ganguly
Currently associated as a Junior Developer at Protech Infosystems Pvt. Ltd, Kolkata. Kuntal has expertise in using a wide range of open source and commercial tools (WAS CE, Eclipse, Mule ESB, EZlegacy , Active MQ , Birt , and DB2 express C) and technologies(GWT and Android).
Partha Goswami (, Jr. Developer, Protech Infosystems Pvt. Ltd
Partha Goswami
Currently associated as a Junior Developer at Protech Infosystems Pvt. Ltd, Kolkata. Has expertise in using a wide range of open source and commercial tools (WASCE, Eclipse, Mule ESB, EZlegacy , Active MQ , Birt , and DB2 express C) and technologies(GWT and RSS).

Summary:  This tutorial demonstrates how to develop a CXF web service which can upload a submitted file from the user and store it in a specific directory. The example is built with widely used Eclipse IDE.

View more content in this series

Date:  17 Jun 2011
Level:  Intermediate


Configuration and development

This example will show how to configure and develop a CXF based webservice running on a server that would perform uploading of files submitted by the client. See below the following specifications.

Tomcat web server 5.5 or above: The Tomcat servlet engine is an open-source package developed as part of the Apache Software Foundation's Jakarta project. It is the official reference implementation for both the servlet and JSP specifications. Tomcat can act as a stand-alone Web server and also as a servlet/JSP engine. We can download the latest release of Tomcat from

Apache-cxf-2.3. or above: Apache CXF is an open source services framework. CXF helps you build and develop services using frontend programming APIs, like JAX-WS and JAX-RS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI.You can download the lates version from

Eclipse IDE: An integrated development environment (IDE) is an all-in-one tool for writing, editing, compiling, and running computer programs. And Eclipse provides an excellent integrated development environment. You can find the latest release of eclipse in

Set up the Environment

  1. Install Jdk 1.5 or above in your system.
  2. After downloading apache-cxf distribution set the CXF_HOME environment variable.
  3. Download latest version of Tomcat and set the TOMCAT_HOME environment variable.

Create web service

  1. Start Eclipse in JavaEE perspective and select File > New > Other > Dynamic web Project named 'CxfService'.
  2. Expand the CxfService Project tab, select Java Resource: src and create a package ''.
  3. The package '' will contain a simple java bean class which will get and set the name of the file, the type of the file and the DataHandler type. The bean will be passed as a parameter to invoke this service. So create a class under that package and name it as 'FileUploader'. The code listing for this class is given below in Listing 1 and figure 2.

Figure 2. File Uploader bean class
File Uploader bean class

Listing 1.


       import javax.activation.DataHandler;

public class FileUploader
  private String Name;
  private String FileType;
  private DataHandler Dfile;

  public String getName()
    return this.Name;

  public void setName(String Name)
    this.Name = Name;

  public DataHandler getDfile()
    return this.Dfile;

  public void setDfile(DataHandler Dfile)
    this.Dfile = Dfile;

public String getFileType() {
    return FileType;

public void setFileType(String FileType) {
    this.FileType = FileType;

  1. Every web service requires a Service Endpoint Interface (SEI), through which the client can invoke the implementation class. Now select Java Resource: src and create another package named ''.
  2. Create an interface named 'UploadSEI' containing a method named 'uploadFile' as shown in the listing 2 and figure 3.

Figure 3. UploadSEI - Service Endpoint Interface
UploadSEI--Service Endpoint Interface

Listing 2.


import javax.jws.WebParam;
import javax.jws.WebService;

	public interface UploadSEI {
	    void uploadFile(@WebParam(name="Dfile") FileUploader Dfile);

  1. Create a service implementation class named 'UploadServiceImpl' implementing the interface inside the same package ''. This class defines the implementation method uploadFile which uses the FileUploader bean as its parameter. See the figure 4 below and the listing 3.

Figure 4. Upload Service Implementation
Upload Service Implementation

Listing 3.


import javax.activation.DataHandler;
import javax.jws.WebService;


@WebService(endpointInterface = "",
		serviceName = "UploadService")

public class UploadServiceImpl implements UploadSEI{
	public void uploadFile(FileUploader Dfile) {

		DataHandler handler = Dfile.getDfile();
		try {
		    InputStream is = handler.getInputStream();

		    OutputStream os = new FileOutputStream(new File("E:/uploads/"
			    + Dfile.getName() +"."+ 
		    byte[] b = new byte[100000];
		    int bytesRead = 0;
		    while ((bytesRead = != -1) {
			os.write(b, 0, bytesRead);

		} catch (IOException e) {


  1. The "OutputStream" will save the file in desired location as provided.
  2. Next is to create a configuration file 'cxf.xml' that would create a JAX-WS endpoint based on our implementation class 'UploadServiceImpl'. Make sure that the file is in the root 'src' folder, otherwise edit the web.xml according to your path of the file. See figure 5 and listing 4.

Figure 5. CXF configuration file
CXF configuration file

Listing 4. cxf.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

  <import resource="classpath:META-INF/cxf/cxf.xml" />
  <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
  <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
  <jaxws:endpoint id="uploadfile"
      <entry key="mtom-enabled" value="true"/>

  1. Edit the 'web.xml' file in the WEB-INF folder. See listing 5.

Listing 5. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
xsi:schemaLocation="" id="WebApp_ID" version="2.5">

  1. Create a folder named 'lib' under WebContent > WEB-INF (see figure 5) and include the following .jar files in the lib folder. You can find all these jars in the CXF distribution library which you have already downloaded.


Your errors will now disappear. Check in the below figure 6.

Figure 6. CXF configuration file
CXF configuration file
  1. Right click the project select Export > WAR file (see figure 7). Copy the WAR file and paste it in the webapps directory under Tomcat_Home. Start the Tomcat server.

Figure 7. WAR creation
WAR creation
  1. On starting the tomcat server the Web service gets deployed in it. Go to the Tomcat Manager, enter username, password and log into it. You will find the deployed service named 'CxfService', click onto it and you will find the available service with its WSDL location. Click on the location hyperlink to see the WSDL. See figure 8.

Figure 8. Tomcat Console
Tomcat Console

Service Endpoint - http://localhost:8080/CxfService/UploadWS
WSDL location - http://localhost:8080/CxfService/UploadWS?wsdl

Generate the Stubs

In order to invoke the service the client must know the Service Endpoint Interface and the bean file which is to be invoked as a parameter. In order to get the things the client can create stubs from the WSDL of the service.

CXF distribution provides a tool called 'wsdl2java.bat' which can create the stubs for a particular service when provided the WSDL location with some additional parameters.

Go to the bin directory of $(CXF_HOME) from the command prompt and type the following command.

wsdl2java –client –verbose http://localhost:8080/CxfService/UploadWS?wsdl

This is going to run the wsdl2java.bat file present in the bin directory. The '-client' option generates starting point code for a client mainline. The '–verbose' option displays comments during the code generation process. See figure 9.

On successful execution of the command you will find the stubs created under the package '' in the $(CXF_HOME)/bin directory.

Figure 9. Stub Generation Command
Stub Generation Command

Create The Client

Now we are going to create the client project so that the web service can be consumed. In this example the client is a POJO client, you can also make a web client which would require a web container to run. Follow the below steps to develop a client.

  1. In Eclipse select File > New > Other > Dynamic web project and create a new project named 'CxfClient'.
  2. Create a package named '' (as in the stubs) and copy-paste all the generated stubs in it.
  3. Create another package named ''. Create a new class named 'Client' in the package. This class is going to invoke the developed service through the generated stubs. This class will contain the main() method so execution will start from here. See the code listing 6 for this class.

Figure 10. Client invoking service java class
Client invoking service java class

Listing 6.


import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;


public final class Client {


    public static void main(String args[]) throws Exception {

    	JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

    	factory.getInInterceptors().add(new LoggingInInterceptor());
    	factory.getOutInterceptors().add(new LoggingOutInterceptor());
    	UploadSEI client =(UploadSEI) factory.create();

    	FileUploader file=new FileUploader();
    	DataSource source = new FileDataSource(new File("D:/my_upload_doc.doc"));
    	file.setDfile(new DataHandler(source));


  1. Do not forget to include the previously mentioned .jar files in the WebContent > WEB-INF > lib.
  2. The 'DataSource' object source will contain the desired location of your uploading file. Here it is 'D:/my_upload_doc.doc' change it according to your file.
  3. The setName("Partha") will be the saving name of the uploaded file. Set the file type accordingly by modifying the setFileType("doc") parameter.
  4. You still might get a type mis-match error in 'file.setDfile', this might be because the generated stub '' has been having a 'byte[]' variable instead of having a 'DataHandler' variable .Change the byte[] to DataHander to resolve this problem. You should also import 'javax.activation.DataHandler' in it. In any inconvenience refer to the bean class used during the service creation in Listing 1.
  5. To run the client right-click on the file and select Run as > Java Application. If everything is perfect then you will find your file in saved by the given name in the location specified in the service.

3 of 7 | Previous | Next


Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

Zone=SOA and web services
TutorialTitle=Developing web services, Part 3: File uploading web service built with Apache CFX


Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).