This tutorial shows how we can send file using SOAP based webservice. The type of the file can be anything, i.e., text, image, pdf, MS doc etc. For this type of application we need to create two applications – one will work as a client application(which sends a file) and other one will work as a server application(which receives a file). So the server application will deploy the service whereas client application will consume the service. In server application we will have logic for what will be done with the file content after receiving the file. Using the client application we will upload the file and send through the SOAP service.

In this example both client and server applications are web based application. In client application we will upload the file using JSP, Servlet and send it to the server application which then saves the received file to the specific location on disk.

Please feel free to contact me for any kind of help.

Final Output

Home page

SOAP File Attachment

When no file selected for upload

SOAP File Attachment

When a file is selected and sent

SOAP File Attachment

Prerequisites

Tomcat v7
Eclipse
JDK 1.6

jars for server application

SOAP File Attachment

jar for client application

activation.jar

We will now look at the server and client applications how they get created.

First and foremost step is to create Dynamic Web Project in Eclipse for both server(project name : soap-send-file) and client(project name : upload-file) application.

Server Application

Step 1. After creating the project in Eclipse, put all jars under WEB-INF/lib directory.

Step 2. Create endpoint interface with the below source code

package in.webtuts.service;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface FileSendService {

    @WebMethod
    String sendFile(byte[] fileContent, String fileName);

}

 

Step 3. Create endpoint implementation for endpoint service.

package in.webtuts.service;

import in.webtuts.utils.FileUtils;

import javax.jws.WebService;

@WebService(endpointInterface = "in.webtuts.service.FileSendService")
public class FileSendServiceImpl implements FileSendService {

    @Override
    public String sendFile(byte[] fileContent, String fileName) {

        boolean response = FileUtils.saveFile(fileContent, fileName);

        if (response) {
            return "File successfully received and saved to disk!";
        }

        return "OOPs! some error occurred.";
    }

}

 

Step 4. Create Constants.java

package in.webtuts.utils;

public class Constants {

    public static final int BUFFER_SIZE = 1024;
    public static final String FILE_SAVE_PATH = "D:/sworkspace";

}

 

Step 5. Create FileUtils.java

package in.webtuts.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileUtils {

    public static boolean saveFile(byte[] fileContent, String fileName) {
        OutputStream outputStream = null;

        try {
            File file = new File(Constants.FILE_SAVE_PATH + File.separator
                    + fileName);
            outputStream = new FileOutputStream(file);
            outputStream.write(fileContent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }

}

 

Step 6. Create sun-jaxws.xml file with the below content and put it under WEB-INF directory

<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
    version="2.0">
    <endpoint name="SoapFileSend" implementation="in.webtuts.service.FileSendServiceImpl"
        url-pattern="/SoapFileSend" />
</endpoints>

 

Step 7. Modify web.xml file as below

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>soap-send-file</display-name>
  <listener>
    <listener-class>
        com.sun.xml.ws.transport.http.servlet.WSServletContextListener
     </listener-class>
  </listener>
  <servlet>
    <servlet-name>SoapFileSend</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SoapFileSend</servlet-name>
    <url-pattern>/SoapFileSend</url-pattern>
  </servlet-mapping>
</web-app>

 

Step 8. We need to generate request and response structure. So navigate to the root directory of the project and execute the below command from command prompt.

<disk location>\soap-send-file>wsgen -s src -d build/classes -cp build/classes in.webtuts.service.FileSendServiceImpl

 

Step 9. Now run the application. Hit the URL http://<host>:<port>/<context path>/<URL pattern>?wsdl, i.e., http://localhost:8080/soap-send-file/SoapFileSend?wsdl. You will get the below wsdl file in the browser

<?xml version="1.0" encoding="UTF-8"?><!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2-b05-. --><!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2-b05-. --><definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://service.roytuts.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://service.roytuts.com/" name="FileSendServiceImplService">
    <types>
        <xsd:schema>
        <xsd:import namespace="http://service.roytuts.com/" schemaLocation="http://localhost:8080/soap-send-file/SoapFileSend?xsd=1"></xsd:import>
        </xsd:schema>
    </types>
    <message name="sendFile">
        <part name="parameters" element="tns:sendFile"></part>
    </message>
    <message name="sendFileResponse">
        <part name="parameters" element="tns:sendFileResponse"></part>
    </message>
    <portType name="FileSendService">
        <operation name="sendFile">
            <input wsam:Action="http://service.roytuts.com/FileSendService/sendFileRequest" message="tns:sendFile"></input>
            <output wsam:Action="http://service.roytuts.com/FileSendService/sendFileResponse" message="tns:sendFileResponse"></output>
        </operation>
    </portType>
    <binding name="FileSendServiceImplPortBinding" type="tns:FileSendService">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"></soap:binding>
        <operation name="sendFile">
            <soap:operation soapAction=""></soap:operation>
            <input>
                <soap:body use="literal"></soap:body>
            </input>
            <output>
                <soap:body use="literal"></soap:body>
            </output>
        </operation>
    </binding>
    <service name="FileSendServiceImplService">
        <port name="FileSendServiceImplPort" binding="tns:FileSendServiceImplPortBinding">
            <soap:address location="http://localhost:8080/soap-send-file/SoapFileSend"></soap:address>
        </port>
    </service>
</definitions>

 

Now we will see how we can consume the service and send file to the above application.

Client Application

Step 1. After creating a project in Eclipse, put the jar activation.jar under WEB-INF/lib directory

Step 2. Modify the deployment descriptor file – web.xml as follows. We won’t put any entry for servlet in this file because we are using servlet 3 so using annotation is enough.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>upload-file</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

 

Step 3. Now generate stub or client from wsdl file. So do right-click on the client project(upload-file) and choose Web Services -> Web Service Client. Click Next. Put the URL http://localhost:8080/soap-send-file/SoapFileSend?wsdl for “Service Definition:” on the next window. Make sure “Deploy Client” is selected for client generation as shown below picture.

SOAP File Attachment

You can also select local wsdl file for “Service Definition:” using “Broswe” button. Click Next. Click Finish. The required client files are generated under in.webtuts.service package.

Step 4. Now create a view – index.jsp which will give user an opportunity to upload a file for sending using SOAP webservice.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload and Send File using SOAP Webservice - Servlet Example</title>
</head>
<body>
    <div style="width: 600px;">
        <c:if test="${!empty error}">
            <p style="color: red;">
                <c:out value="${error}" />
            </p>
        </c:if>
        <c:if test="${!empty success}">
            <p style="color: green;">
                <c:out value="${success}" />
            </p>
        </c:if>
        <form method="post" action="Upload" enctype="multipart/form-data">
            <fieldset>
                <legend>Upload File</legend>
                <p>
                    <label>Select File</label><br /> <input type="file" name="file"
                        id="file" />
                </p>
                <p>
                    <input type="submit" name="uploadFile" value="Upload File" />
                </p>
            </fieldset>
        </form>
    </div>
</body>
</html>

 

Step 5. Create UploadUtils.java file which holds some utility methods.

package in.webtuts.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.Part;

public class UploadUtils {

    public static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }

    public static byte[] getFileContent(InputStream inputStream) {
        try {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int reads = inputStream.read();

            while (reads != -1) {
                baos.write(reads);
                reads = inputStream.read();
            }

            return baos.toByteArray();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

 

Step 6. Create a servlet which will upload the file and send to the server application using SOAP service.

package in.webtuts.servlets;

import in.webtuts.service.FileSendService;
import in.webtuts.service.FileSendServiceImplService;
import in.webtuts.service.FileSendServiceImplServiceLocator;
import in.webtuts.utils.UploadUtils;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.xml.rpc.ServiceException;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/Upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        Part filePart = request.getPart("file");
        String uploadSubmit = request.getParameter("uploadFile");
        String fileName = UploadUtils.getFilename(filePart);

        if (uploadSubmit != null && fileName != null && fileName.length() > 0) {
            InputStream inputStream = filePart.getInputStream();
            byte[] fileContent = UploadUtils.getFileContent(inputStream);
            FileSendServiceImplService service = new FileSendServiceImplServiceLocator();
            try {
                FileSendService fileSendService = service
                        .getFileSendServiceImplPort();
                String resp = fileSendService.sendFile(fileContent, fileName);
                if (!resp.contains("OOPs")) {
                    request.setAttribute("success", resp);
                } else {
                    request.setAttribute("error", resp);
                }
            } catch (ServiceException e) {
                e.printStackTrace();
            }
        } else {
            String msg = "OOPs! You must select a file to upload.";
            request.setAttribute("error", msg);
        }

        RequestDispatcher requestDispatcher = request
                .getRequestDispatcher("/index.jsp");
        requestDispatcher.forward(request, response);

    }

}

 

Step 7. Now run the application.

Note:  Please run the server application first in order to receive and save the file onto disk.

Thanks for your reading. Please do not forget to leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

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