Solved

uploading file in JNLP application

Posted on 2010-11-17
18
1,192 Views
Last Modified: 2013-11-24
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

0
Comment
Question by:mock5c
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
  • 5
18 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 50 total points
ID: 34158371
You need to implement doPost in a servlet and call the servlet from your JWS app using a POST:

http://www.exampledepot.com/egs/java.net/Post.html
0
 
LVL 92

Expert Comment

by:objects
ID: 34159620
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
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34160266
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)
0
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 

Author Comment

by:mock5c
ID: 34160523
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?
0
 
LVL 92

Expert Comment

by:objects
ID: 34160571
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/
0
 

Author Comment

by:mock5c
ID: 34160618
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 :)
0
 
LVL 92

Expert Comment

by:objects
ID: 34160649
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.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34160661
Although not secure, it can be as simple as this:

http://www.codeguru.com/forum/printthread.php?t=289310
0
 
LVL 92

Expert Comment

by:objects
ID: 34160727
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
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34160737
(Which is what i've just mentioned)
0
 

Author Comment

by:mock5c
ID: 34160891
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?
0
 
LVL 92

Assisted Solution

by:objects
objects earned 450 total points
ID: 34160909
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);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34163142
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
0
 

Author Comment

by:mock5c
ID: 34169542
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

0
 
LVL 92

Expert Comment

by:objects
ID: 34169577
don't reinvent the wheel, use fileupload or cos on the client to handle the upload (theres a link in my earlier comment)
0
 
LVL 92

Expert Comment

by:objects
ID: 34169583
And theres nothing cumbersome about the approach you are taking. In fact its fairly standard
0
 

Author Comment

by:mock5c
ID: 34169830
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.
0
 
LVL 92

Accepted Solution

by:
objects earned 450 total points
ID: 34169869
sorry above should have referred you to httpclient for handling the client side
theres an example here
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/MultipartFileUploadApp.java?view=markup
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

710 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question