uploading file in JNLP application

The last piece of the puzzle for my application is uploading a file to a web server.  I already have in place the creation of a list of files that are compressed into a single file and this zip file is created on a the local computer.  Now I need to get these files uploaded to the server.  I'll admit that I'm completely clueless  when it comes to client-server development.

I've searched the web to find some examples and have not found much other than I need to have a servlet running.  I've attached some code that was provided to me but I don't believe that is what I need.  I also found links such as http://www.prasannatech.net/2008/11/http-web-server-java-post-file-upload.html which may help me.

But exactly how do I call these servlets from java code?  This is a web start application and does not involve a browser.  As I said earlier, I have compressed the file and have my hands on it, I'm just not sure how to get it to the server or how to hand it off to the servlet.

Thank you for your assistance.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

 * This is a shell that will handle upload. 
public class Upload extends HttpServlet {

     * This method writes the most commonly used request information
     * to the response body, such as the User-Agent header, the
     * various paths associated with the request, and the request
     * parameters.
    public void doGet(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

        String name = request.getParameter("name");
        if (name == null) {
            name =  "you";
        PrintWriter out = response.getWriter();
        out.println("<h1>Hello " + name + "</h1>");

        out.println("I see that:<ul>");
        String userAgent = request.getHeader("User-Agent");
        out.println("<li>your browser is: " + userAgent);
        String requestURI = request.getRequestURI();
        out.println("<li>the URI for this page is: " +
        String contextPath = request.getContextPath();
        out.println("<li>the context path for this app is" +
        String servletPath = request.getServletPath();
        out.println("<li>this servlet is mapped to: " +
        String pathInfo = request.getPathInfo();
        out.println("<li>the remaining path is: " + pathInfo);
        Map parameters = request.getParameterMap();
        out.println("<li>you sent the following params:<ul>");
        Iterator i = parameters.keySet().iterator();
        while (i.hasNext()) {
            String paramName = (String) i.next();
            out.println("<li><b>" + paramName + "</b>:");
            String[] paramValues =
                (String[]) parameters.get(paramName);
            for (int j = 0; j < paramValues.length; j++) {
                if (j != 0) {
                    out.print(", ");

Open in new window

Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

objectsConnect With a Mentor Commented:
sorry above should have referred you to httpclient for handling the client side
theres an example here
CEHJConnect With a Mentor Commented:
You need to implement doPost in a servlet and call the servlet from your JWS app using a POST:

you can POST it to your servlet, but better offer doing a file upload

you can use commons fileupload to handle the upload in your servlet

and httpclient or cos to upload the file from your application

let me know if you have any queestions
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

mock5c, you should understand that if you want to make life simpler (simpler even than the method i mentioned originally) you should use a protocol that's designed for transferring files, such as scp, sftp, ftp. File transfer via web pages is a kludgy bolt-on to the http protocol and is neither simple, nor secure (unless done over https)
mock5cAuthor Commented:
I am all for making life simpler.  sFTP is an option since it's secure and I have an sftp site available.  Can this be any sftp site or must it be the same as the web server?  This is also JNLP application, in case I have not mentioned that.  Do you have any examples of using sFTP?
you'll find what i posted above is the simplest

to use ftp you can use something like commons net
mock5cAuthor Commented:
objects, I assume that your suggestion works with the jnlp application.

Perhaps CEHJ and objects should have a battle of the "simplest" and post their code here :)
the code for all the options I have posted is straightforward and lots of standard solutions exist. more a question of how you want to handle the upload on the server side. Using a servlet would be the most flexible.
So pick how you want to transfer the file then use the appropriate api (see the links I posted above) to implement it.
Although not secure, it can be as simple as this:

you can use the URL class for ftping , but its not the nicest

(Which is what i've just mentioned)
mock5cAuthor Commented:
I'm basically scrambling and looking at all of these options.  With apache commons FileUpload, it's not exactly clear where DiskFileItemFactory, ServletFileUpload, etc. are defined since they do not provide complete examples.  I'm assuming this is inside the doPost() servlet method.  Is this correct?
objectsConnect With a Mentor Commented:
yes in your doPost and pass the request to ServletFileUpload.parseRequest() for processing

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure the factory here, if desired.
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Configure the uploader here, if desired.
        List fileItems = upload.parseRequest(request);
Of all ways to do it, that's the most cumbersome. Bear in mind too that without authentication, *anyone* will be able to upload stuff, with whatever consequences that might entail
mock5cAuthor Commented:
I hear you on some methods being more cumbersome than others.  I am trying out a few of these suggestions.  For the commons net method, my sample code is below.  I would appreciate it if anyone could make suggestions on how to work through my problems.  I am getting log information on the server that reports:

From (ServerResponse): java.io.IOException: Server returned HTTP response code: 500 for URL: ...

My objective is simply to send large zip files from the client JNLP/Webstart application to a server where they are stored on disk.  At the moment I am not concerned about processing the file or inserting data into a database.  Eventually I'll probably want to unzip the file but that is not something I'm worried about.  Getting the file uploading working is my priority.



   public void doPost(HttpServletRequest req, HttpServletResponse res) {

      System.out.println("... In Upload.doPost() ...");

      try {   
         DiskFileItemFactory factory = new DiskFileItemFactory();
         ServletFileUpload upload = new ServletFileUpload(factory);

         // maximum size that will be stored in memory
         // the location for saving data that is larger than getSizeThreshold()
         //factory.setRepository(new File("/tmp"));

         List items = upload.parseRequest(req);

         String fileName = "";
         long maxSize = 0;
         Iterator iter = items.iterator();
         while (iter.hasNext()) {
            DiskFileItem item = (DiskFileItem) iter.next();

            // filename on the client
            fileName = item.getName();
            maxSize = item.getSize();

            // write the file
            item.write(new File("/tmp", fileName));
      catch(Exception e) {
         System.out.println("<br>\nError: "+e.getMessage());

// test app

import java.io.*;
import java.net.*;

public class UploadTest  {
  public static void main(String[] args) throws Exception { 
    HttpURLConnection conn = null; 
    BufferedReader br = null; 
    DataOutputStream dos = null; 
    DataInputStream inStream = null; 

    InputStream is = null; 
    OutputStream os = null; 
    boolean ret = false;
    String StrMessage = "";
    String fileName = "C:\\test.zip";

    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer; 
    int maxBufferSize = 1*1024*1024;
    String responseFromServer = "";
    String urlString = "http://localhost:8080/FileUpload/requestupload";

    try {   
      //------------------ CLIENT REQUEST 
      FileInputStream fileInputStream = new FileInputStream(new File(fileName));

      // open a URL connection to the Servlet 
      URL url = new URL(urlString);
      System.out.println("url = " +url);

      // Open a HTTP connection to the URL 
      conn = (HttpURLConnection) url.openConnection();
      System.out.println("conn = " + conn);

      // Allow Inputs

      // Allow Outputs 

      // Don't use a cached copy.

      // Use a post method. 
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

      dos = new DataOutputStream( conn.getOutputStream() );
      dos.writeBytes(twoHyphens + boundary + lineEnd);
      dos.writeBytes("Content-Disposition: form-data; name=\"upload\";"
         + " filename=\"" + fileName +"\"" + lineEnd);

      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];

      bytesRead = fileInputStream.read(buffer, 0, bufferSize);

      while (bytesRead > 0) {
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

      // send multipart form data necesssary after file data... 

      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    catch (MalformedURLException ex) {
      System.out.println("From ServletCom CLIENT REQUEST:"+ex);

   catch (IOException ioe) {

     System.out.println("From ServletCom CLIENT REQUEST:"+ioe);

   //------------------ read the SERVER RESPONSE

   try {
     inStream = new DataInputStream ( conn.getInputStream() );
     String str;
     while (( str = inStream.readLine()) != null) {
       System.out.println("Server response is: "+str);
   catch (IOException ioex) {
     System.out.println("conn = " + conn);
     System.out.println("From (ServerResponse): "+ioex);

Open in new window

don't reinvent the wheel, use fileupload or cos on the client to handle the upload (theres a link in my earlier comment)
And theres nothing cumbersome about the approach you are taking. In fact its fairly standard
mock5cAuthor Commented:
what do you mean by "cos"?

In the servlet code, which I basically got from commons FileUpload site and am trying to piece together, the line:

List items = upload.parseRequest(req)

seems to be a problem.  I have print statements before and after and the lines after do not print anything.
All Courses

From novice to tech pro — start learning today.