Link to home
Start Free TrialLog in
Avatar of mock5c
mock5c

asked on

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";
        }
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        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: " +
            requestURI);
        String contextPath = request.getContextPath();
        out.println("<li>the context path for this app is" +
            contextPath);
        String servletPath = request.getServletPath();
        out.println("<li>this servlet is mapped to: " +
            servletPath);
        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(", ");
                }
                out.print(paramValues[j]);
            }
        }
        out.println("</ul></ul></body></html>");
    }
}

Open in new window

SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
http://commons.apache.org/fileupload/

and httpclient or cos to upload the file from your application

let me know if you have any queestions
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)
Avatar of mock5c
mock5c

ASKER

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
http://commons.apache.org/net/
Avatar of mock5c

ASKER

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:

http://www.codeguru.com/forum/printthread.php?t=289310
you can use the URL class for ftping , but its not the nicest

http://helpdesk.objects.com.au/java/how-to-access-ftp-server-using-url-class
(Which is what i've just mentioned)
Avatar of mock5c

ASKER

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?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of mock5c

ASKER

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.

Nathan


//Servlet

   public void doPost(HttpServletRequest req, HttpServletResponse res) {

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

      try {   
         DiskFileItemFactory factory = new DiskFileItemFactory();
         ServletFileUpload upload = new ServletFileUpload(factory);
         upload.setSizeMax(100000000);

         // maximum size that will be stored in memory
         //factory.setSizeThreshold(1096);
         // 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
      conn.setDoInput(true);

      // Allow Outputs 
      conn.setDoOutput(true);

      // Don't use a cached copy.
      conn.setUseCaches(false);

      // Use a post method. 
      conn.setRequestMethod("POST");
      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);
      dos.writeBytes(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(lineEnd);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

      fileInputStream.close();
      dos.flush();
      dos.close();
    }
    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);
       System.out.println("");
     }
     inStream.close();
   }
   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
Avatar of mock5c

ASKER

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.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial