Passing a file as parameter from applet to servlet

hi
i have just started to use servlets. i have developed applet gui interface. when i click the button i want a file "abc.txt" to be send to the servlet. i am doing like this:
URL serv_url = new URL(null,"http://host:port/xyz/servlet/TestServlet);
URLConnection connect = (URLConnection)serv_url.openConnection();
output = new File("abc.txt");
connect.setDoOutput(true);
connect.setDoInput(true);
connect.setUseCaches(false);
connect.setDefaultUseCaches(false);
connect.setRequestProperty("content-type","application/x-www-form-urlencoded");
ObjectOutputStream outputToServlet = new ObjectOutputStream(connect.getOutputStream());
outputToServlet.writeObject(output);
outputToServlet.flush();
outputToServlet.close();
//for printing purpose on the gui listbox          
listmodel1.addElement("ConnectingToRemoteServlet");
BufferedReader in = new BufferedReader ( new InputStreamReader (connect.getInputStream()));
          while((line = in.readLine())!= null)
          listmodel1.addElement("Response:"+line);
          in.close();
but i am not sure if this is correct. because when i tried to print the file that is send to servlet. it is giving some ascii characters...
please tell me how to make sure if the file has reached the servlet. or any other method!!
thanks
pre_pra

i don't want to use any third party packages to achieve this. I have looking into forums and i understand that some object serialization stuff has to be done. but i am still not clear abt how to proceed. any example code or details of steps regarding to pass file object from applet to the servlet would be greatly appreciated. i have already spend two full days on this. i wish i can get a better understanding wiht you help
thanks a lot:)

Similar Messages

  • Problem in sending image from applet to servlet

    dear friends,
    i have a need to send an image from applet to servlet via HttpConnection and getting back that image from applet.
    i am struggling with this sice many hours and got tired by searching any post that would help me but haven't got yet.
    i tried using this code but it dosent make any execution sit right. i got NPE at ImageIcon.getDescription() line;
    at applet side
          jf.setContentPane(getJContentPane());
                     FileDialog fd=new FileDialog(jf,"hi");
                     fd.setMode(FileDialog.LOAD);
                     fd.setVisible(true);   
                     v=new Vector();
                     try{                                                
                               FileInputStream fis=new FileInputStream(new File(fd.getDirectory()+fd.getFile()));      
                               byte[] imgbuffer=new byte[fis.available()];
                               fis.read(imgbuffer);
                               ImageIcon imgdata=new ImageIcon(imgbuffer);
                               v.add(0,imgicon);
                                String strwp ="/UASProject/Storeimage";              
                                URL servletURL = new URL(getCodeBase(),strwp);             
                                HttpURLConnection servletCon = (HttpURLConnection)servletURL.openConnection();       
                                servletCon.setDoInput(true); 
                                servletCon.setDoOutput(true);
                                servletCon.setUseCaches(false);
                                servletCon.setDefaultUseCaches(false);   
                                servletCon.setRequestMethod("POST");     
                                servletCon.setRequestProperty("Content-Type", "application/octet-stream");   
                                servletCon.connect();            
                                ObjectOutputStream oboutStream = new ObjectOutputStream(servletCon.getOutputStream());                     
                                oboutStream.writeObject(v);
                                v.remove(0);
                                oboutStream.flush();      
                                oboutStream.close();  
                                //read back from servlet
                                ObjectInputStream inputStream = new ObjectInputStream(servletCon.getInputStream());
                                 v= (Vector)inputStream.readObject();                     
                                 imgicon=(ImageIcon)v.get(1);
                                 showimg.setIcon(imgicon);
                                 this.getContentPane().validate();
                                 this.validate();  
                                inputStream.close();                                                        
                             //  repaint();
                     }catch(Exception e){e.printStackTrace();}  and this is at servlet side
            try {       
                         Vector v=new Vector();                    
                         ObjectInputStream inputFromjsp = new ObjectInputStream(request.getInputStream());                                      
                          v = (Vector)inputFromjsp.readObject();                                                                                                          
                          imgicon=(ImageIcon)v.get(0);                     
                          inputFromjsp.close();            
                          System.out.println(imgicon.getDescription());                                      
                          v.remove(0);
                          v.add(1,imgicon);
    //sending back to applet
                           response.setContentType("application/octet-stream");
                          ObjectOutputStream oboutstream=new ObjectOutputStream(response.getOutputStream());            
                          oboutstream.writeObject(v);
                          oboutstream.flush();
                          oboutstream.close();
                   } catch (Exception e) {e.printStackTrace();}  i really need your help. please let me out of this headche
    thanks
    Edited by: san_4u on Nov 24, 2007 1:00 PM

    BalusC wrote:
    san_4u wrote:
    how can i made a HttpClient PostMethod using java applets? as i have experience making request using HttpURLConnection.POST method. ok first of all i am going make a search of this only after i will tell. please be onlineOnce again, see link [3] in my first reply of your former topic.
    yeah! i got the related topic at http://www.theserverside.com/tt/articles/article.tss?l=HttpClient_FileUpload. please look it, i am reading it right now and expecting to be reliable for me.
    well what i got, when request made by html code(stated above) then all the form fields and file data mixed as binary data and available in HttpServletRequest.getinputstream. and at servlet side we have to use a mutipart parser of DiskFileItemFactory class that automatically parse the file data and return a FileItem object cotaing the actual file data,right?.You can also setup the MultipartFilter in your environment and don't >care about it further. Uploaded files will be available as request attributes in the servlet.is the multipartfilter class file available in jar files(that u suggested to add in yours article) so that i can use it directly? one more thing the import org.apache.commons.httpclient package is not available in these jar files, so where can got it from?
    one mere question..
    i looked somewhere that when we request for a file from webserver using web browser then there is a server that process our request and after retrieving that file from database it sends back as response.
    now i confused that, wheather these webservers are like apache tomcat, IBM's webspher etc those processes these request or there is a unique server that always turned on and process all the request?
    because, suppose in an orgnisation made it's website using its own server then, in fact, all the time it will not turned on its server or yes it will? and a user can make a search for kind of information about this orgnisation at any time.
    hopes, you will have understand my quary, then please let me know the actual process
    thanks
    Edited by: san_4u on Nov 25, 2007 11:25 AM

  • Sending a file from Applet to servlet HELP me Please

    Sorry, i have the problem this is my code Applet & Servlet but it seems working asynchronously if you have some ideas please reply me i send bytes on outputstream but the inputstream of servlet receive nothing bytes but write my system.out.print on screen server:
    Applet:
    URL servletURL = new URL(codebase, "/InviaFile/servlet/Ricevi");
    HttpURLConnection urlConnection = (HttpURLConnection) servletURL.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    urlConnection.setRequestProperty("Content-length", String.valueOf(100));
    urlConnection.connect();
    if(urlConnection.HTTP_BAD_REQUEST == HttpURLConnection.HTTP_BAD_REQUEST){
    /*System.out.println("Cattiva Richiesta: "+urlConnection.getContentEncoding());
    System.out.println("Tipo di metodo: "+urlConnection.getRequestMethod());
    System.out.println("Tipo di Risposta: "+urlConnection.getResponseCode());
    System.out.println("Tipo di messaggio: "+urlConnection.getResponseMessage());
    System.out.println("Tipo di contenuto: "+urlConnection.getContentType());
    System.out.println("Tipo di lunghezza contenuto: "+urlConnection.getContentLength());
    System.out.println("Tipo di doinput: "+urlConnection.getDoInput());
    System.out.println("Tipo di doouput: "+urlConnection.getDoOutput());
    System.out.println("Tipo di URL: "+urlConnection.getURL());
    System.out.println("Tipo di propriet� richiesta: "+urlConnection.getRequestProperty("Content-Type"));
    System.out.println("Entra if");
    DataOutputStream dout = new DataOutputStream(urlConnection.getOutputStream());
    InputStream is = urlConnection.getInputStream();
    if(ritornaFile("C:/Ms.tif", dout))System.out.println("Finita lettura");
    dout.close();
    urlConnection.disconnect();
    System.out.println("Fine Applet");
    }catch(Exception e) { System.err.println(e.getMessage());e.printStackTrace();}
    public boolean ritornaFile(String file, OutputStream ots)throws Exception{
    FileInputStream f = null;
    try{
    f = new FileInputStream(file);
    byte[] buf = new byte[4 * 1024];
    int byteLetti;
    while((byteLetti = f.read()) != -1){ots.writeByte(buf, 0, byteLetti);ots.flush();
    while((byteLetti = f.read()) != -1){ots.write(byteLetti);ots.flush();
    System.out.println("byteLetti= "+byteLetti);
    return true;
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    return false;
    }finally{
    if(f != null)f.close();
    Servlet:
    HttpSession ses = request.getSession(true);
    System.out.println("Passa servlet "+request.getMethod());
    System.out.println("Passa servlet "+ses.getId());
    ServletInputStream servletinputstream = request.getInputStream();
    DataInputStream dis = new DataInputStream(request.getInputStream());
    int c = dis.available();
    System.out.println("c="+c);
    //ServletOutputStream servletoutputstream
    //response.getOutputStream();
    response.setContentType("application/octet-stream");
    System.out.println("URI= "+request.getRequestURI());
    System.out.println("pathTranslated: "+request.getPathTranslated());
    System.out.println("RemoteUser: "+request.getRemoteUser());
    System.out.println("UserInRole: "+String.valueOf(request.isUserInRole("")));
    System.out.println("pathInfo: "+request.getPathInfo());
    System.out.println("Protocollo: "+request.getProtocol());
    System.out.println("RemoteAddr:"+request.getRemoteAddr());
    System.out.println("RemoteHost:"+request.getRemoteHost());
    System.out.println("SessionID:"+request.getRequestedSessionId());
    System.out.println("Schema:"+request.getScheme());
    System.out.println("SeesionValido:"+String.valueOf(request.isRequestedSessionIdValid()));
    System.out.println("FromURL:"+String.valueOf(request.isRequestedSessionIdFromURL()));
    int i = request.getContentLength();
    System.out.println("i: "+i);
    ritornaFile(servletinputstream, "C:"+File.separator+"Pluto.tif");
    System.out.println("GetMimeType= "+getServletContext().getMimeType("Ms.tif"));
    InputStream is = request.getInputStream();
    int in = is.available();
    System.out.println("Legge dallo stream in="+in);
    DataInputStream diss = new DataInputStream(servletinputstream);
    int ins = diss.read();
    System.out.println("Legge dallo stream ins="+ins);
    int disins = diss.available();
    System.out.println("Legge dallo stream disins="+disins);
    is.close();
    System.out.println("Fine Servlet");
    catch(Exception exception) {
    System.out.println("IOException occured in the Server: " + exception.getMessage());exception.printStackTrace();
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    public void ritornaFile(InputStream its, String fileDest )throws Exception{
    FileOutputStream f = null;
    try{
    f = new FileOutputStream(fileDest);
    byte[] buf = new byte[2 * 1024];
    int byteLetti;
    while((byteLetti = its.read()) != -1){
    f.write(buf, 0, byteLetti);
    f.flush();
    System.out.println("Byteletti="+byteLetti);
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    }finally{
    if(f != null)f.close();

    Hi all,
    Can anyone help me.I am trying to send an audio file from a applet to servlet with HTTP method(no raw sockets), also the servlet shld be able to save the file on the server.Any suggestions welcome.USing audiostream class from javax.sound.sampled.
    The part of applet code which calls servlet is :
    URL url = new URL("http://" + host + "/" + context + "/servlet/UserUpdateWorkLogAudio?userid=" + userId.replace(' ', '+') + "&FileName=" + filename.replace(' ', '+'));
    URLConnection myConnection = url.openConnection();
    myConnection.setUseCaches(false);
    myConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    myConnection.connect();
    out = new BufferedOutputStream(myConnection.getOutputStream());
    AudioSystem.write(audioInputStream, fileType,out); // IS THIS RIGHT APPROACH?
    ************************end of applet code**********************
    ************************servlet code******************************
    try
    {BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    ????????What code shld i write here to get the audio file stream
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
    *********************************************end***********************
    Thanks
    Joe.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Pass byte[] from applet to servlet

    I have an application that allows users to copy an image from the system clipboard into a frame. What I would like to be able to do, is save that image into a database (db2 on as/400). In order to do that, I try to send the image, which I turned into a byte[] in order to easily insert into the database, from the applet to the servlet using streams (no actual file io), but the image always comes up null when I pass it to the servlet. What am I doing wrong? The image gets copied and drawn from the clipboard just fine, but I can't send it to the servlet. I only included the part of the servlet that tries to retreive the byte array. I know the applet code is a little long, but I figured it might be of interest to someone. Please help!
    Here's the code for the applet:
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.datatransfer.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.ImageIcon;
    import java.util.*;
    import java.awt.image.*;
    public class PicApp extends Applet implements ClipboardOwner
    PrintWriter opWriter = null;
    private Button cmdPaste = new Button();
    private ImageControl destinationImage = new ImageControl ();
    private BorderLayout defaultLayout = new BorderLayout ();
    public Image tempImage = null;
    public ImageIcon transferImage = null;
    private String webServerStr = "";
    private String hostName = null;
    private int port = 80;
    private String servletPath = null;
    Clipboard clipboard;
    //the byte array I try to pass
    public byte[] passed = null;
    public String passedAction = null;
    public void init()
    try
    opWriter = new PrintWriter( new BufferedWriter( new FileWriter( "pictureDetails.txt" ) ) );
    catch(Exception e)
    e.printStackTrace();
    hostName = getParameter("HostName");
    servletPath = getParameter("ServletPath");
    passedAction = getParameter("Action");
    //setLayout
    this.setLayout (defaultLayout);
    this.setBackground(java.awt.Color.gray);
    cmdPaste.setLabel("Paste Image from Clipboard");
    this.add (cmdPaste, BorderLayout.SOUTH);
    this.add (destinationImage, BorderLayout.NORTH);
    //add action listener
    cmdPaste.addActionListener (new cmdPasteActionListener ());
    //initialize the clipboard
    clipboard = getToolkit().getSystemClipboard();
    // get the host name and port of the applet's web server
    try
    opWriter.println("Picutre Applet Details\n");
    URL hostURL = getCodeBase();
    opWriter.println("hostURL = " + hostURL.toString() + "\n");
    hostName = hostURL.getHost();
    opWriter.println("hostIP = " + hostName + "\n");
    port = hostURL.getPort();
    opWriter.println("port = " + port + "\n");
    if (port == -1)
    port = 80;
    if(passedAction == "" || passedAction == null)
    webServerStr = "http://" + hostName + ":" + port + servletPath;
    opWriter.println("Web String full = " + webServerStr);
    else
    webServerStr = "http://" + hostName + ":" + port + servletPath + "?act=" + passedAction;
    opWriter.println("Web String full = " + webServerStr);
    opWriter.close();
    catch(Exception e)
    e.printStackTrace();
    // INNER CLASSES
    class cmdPasteActionListener implements ActionListener
    public void actionPerformed (ActionEvent event)
    Transferable clipboardContent = clipboard.getContents(this);
    //Transferable clipboardContent = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    if ((clipboardContent != null) && (clipboardContent.isDataFlavorSupported(DataFlavor.imageFlavor)))
    try
    //display Image
    tempImage = (Image)clipboardContent.getTransferData(DataFlavor.imageFlavor);
    destinationImage.setImage(tempImage);
    int width = (new ImageIcon(tempImage).getIconWidth());
    int height = (new ImageIcon(tempImage).getIconHeight());
    PixelGrabber pg = new PixelGrabber(tempImage, 0, 0, width, height, true);
    passed = new byte[width*height];
    passed = (byte[])pg.getPixels();
    //send Image
    ProcessPicture();
    catch (UnsupportedFlavorException e)
    catch (IOException e)
    }//end of if
    else if(clipboardContent == null)
    }//end of method
    }//end of inner class
    public PicApp()
    public void lostOwnership (Clipboard parClipboard, Transferable parTransferable)
    System.out.println("Lost ownership of clipboard");
    protected void ProcessPicture()
    try
    // connect to the servlet
    URL servletURL = new URL( webServerStr );
    //URLConnection servletConnection = servletURL.openConnection();
    HttpURLConnection servletConnection =(HttpURLConnection)servletURL.openConnection();
    // inform the connection that we will send output and accept input
    servletConnection.setDoInput(true);
    servletConnection.setDoOutput(true);
    // Don't used a cached version of URL connection.
    servletConnection.setUseCaches (false);
    // Specify the content type that we will send binary data
    servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
    // send the image object to the servlet using serialization
    sendImageToServlet(servletConnection);
    // now, let's read the response from the servlet.
    // this is simply a confirmation string
    readServletResponse(servletConnection);
    catch (Exception e)
    System.out.println(e.toString());
    protected void readServletResponse(URLConnection servletConnection)
    BufferedReader inFromServlet = null;
    try
    // now, let's read the response from the servlet.
    // this is simply a confirmation string
    inFromServlet = new BufferedReader(new InputStreamReader(servletConnection.getInputStream()));
    String str;
    while (null != ((str = inFromServlet.readLine())))
    System.out.println("Reading servlet response: " + str);
    inFromServlet.close();
    catch (IOException e)
    System.out.println(e.toString());
    protected void sendImageToServlet(URLConnection servletConnection)
    ObjectOutputStream outputToServlet = null;
    try
    // send the image object to the servlet using serialization
    outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
    //check size of image
    System.out.println(passed.length);
    // write objectt
    outputToServlet.writeObject(passed);
    outputToServlet.flush();
    outputToServlet.close();
    catch (IOException e)
    System.out.println(e.toString());
    servlet:
    public void performTask(HttpServletRequest request, HttpServletResponse response)
    ObjectInputStream inputFromApplet = null;
    byte[] ImageFromApplet = null;
    PrintWriter out = null;
    BufferedReader inTest = null;
    try
    // get an input stream from the applet
    inputFromApplet = new ObjectInputStream(request.getInputStream());
    // read the serialized imageIcon data from applet
    ImageFromApplet = (byte[])inputFromApplet.readObject();
    inputFromApplet.close();
    catch(Exception e)
    // handle exception
    byte[] transferImage = ImageFromApplet;
    if(transferImage == null)
    System.out.println("Image passed is empty!");

    D,
    I read your code. I believe you are trying to send the byte array with the wrong outputStream.write method. For a byte[] I have successfully used the form, servletOut.write(byteArray, 0, byteArray.length). You have to tell the receiver how much data will be sent to it so it knows when to stop read in the data.
    Example:
    _url = new java.net.URL(serverURL);
    //Attempt to connect to the host
    java.net.URLConnection connection = _url.openConnection();
    // Initialize the connection
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-type", "application/octet-stream");
    BufferedInputStream fileInputStream = new BufferedInputStream(fIS);
    int nBytesAvailable = fileInputStream.available();
    byte byteArray[] = new byte[nBytesAvailable];
    fileInputStream.read(byteArray, 0, nBytesAvailable);
    fileInputStream.close();
    fIS.close();
    // send data to servlet, get outstream, write data, flush, close.
    DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
    outStream.write(byteArray, 0, nBytesAvailable);
    outStream.flush();
    outStream.close();

  • Problem while sending seriailized  object from applet to servlet

    Hi I m having Object communication between Applet and Servlet.
    I m getting error stack trace as
    java.io.EOFException
         at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
         at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
         at java.io.ObjectInputStream.<init>(Unknown Source)
         at com.chat.client.ObjectClient.write(ObjectClient.java:56)
    at the line
    ObjectInputStream ois = new ObjectInputStream(conn.getInputStream());
    thanks in advance
    Ravi
    the whole code is as follows....
    public Serializable write(Serializable obj) throws IOException,ClassNotFoundException{
              URLConnection conn = serverURL.openConnection();
              conn.setDoOutput(true);
              conn.setDoInput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "java-internal/"+obj.getClass().getName());
              conn.connect();
              ObjectOutputStream oos= null;
              try{
              oos = new ObjectOutputStream(
                   conn.getOutputStream());
                        oos.writeObject(obj);
                   catch(Exception ee){
                                       ee.printStackTrace();
                   finally{
                        if(oos!=null){
                             oos.flush();
                             oos.close();
                        return the reponse to the client
                   ObjectInputStream ois=null;
                   try{
    \\this is the line where i m getting the error               
    ois = new ObjectInputStream(conn.getInputStream());
                             return (Serializable)ois.readObject();
                        catch(Exception ee){
                                            System.out.println("Error in Object Client inputstream ");
                                            ee.printStackTrace();
                                            return null;
                        finally{
                             if(ois!=null){
                                  ois.close();

    Did anyone find a fix to this problem. I am having a similiar problem. Sometimes I receive an EOFException and othertimes I don't. When I do receive an EOFException I check for available() in the stream and it appears 0 bytes were sent to the Servlet from the Applet.
    I am always open to produce this problem when I use File->New in IE my applet loads on the new page.. and then I navigate to a JSP sitting on the same application server. When I go to the Applet on the initial page and try to send an object to the server I get an EOFException. No idea!

  • Passing parameter from applet to portal is failing

    hi all.
    We have an external applet that we can view on the portal. We want to have two parameter (parm1 and parm2) passed from the applet to the gateway and thus have them re-written by the portal gateway.
    When we access the applet from the portal, and View Source inside the browser's window, we see that the gateway URL does not precede the parameter's url:
    we see:
    <PARAM NAME = "param1" VALUE="http://host.domain.com:8080/JUPL/...
    instead of:
    <PARAM NAME = "param1" VALUE="https://http://host.domain.com/http://host.domain.com:8080/JUPL/...
    However, we are following sun docs on how to apply rules for HTML content (As in http://docs.sun.com/source/816-6359-10/rewrtadm.html#23362).
    here's our rule:
         <Applet source="*/applet1.jsp" code="java2.applet1.client.MApplet.class"
         param="param1;param2;"/>
    Any ideas on how to solve this?
    Thanks!

    Here this shold work for ya
    you just have to add a extra text file or what ever but this will give you some ideas
      import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.applet.*;
    import javax.swing.*;
    public class a extends Applet implements ActionListener {
    Button button = new Button("click");
    TextField field = new TextField(20);
    JFrame frame = new JFrame();
      String gg;
    public void init() {
      add(button);
       add(field);
       button.addActionListener(this);
    public void actionPerformed(ActionEvent eve) {
           if(eve.getSource() == button) {
                try{
                         gg = field.getText();
                     JOptionPane.showMessageDialog(frame, gg);
               } catch(Exception e) {}
    }hope this helps

  • Uploading large files from applet to servlet throws out of memory error

    I have a java applet that needs to upload files from a client machine
    to a web server using a servlet. the problem i am having is that in
    the current scheme, files larger than 17-20MB throw an out of memory
    error. is there any way we can get around this problem? i will post
    the client and server side code for reference.
    Client Side Code:
    import java.io.*;
    import java.net.*;
    // this class is a client that enables transfer of files from client
    // to server. This client connects to a servlet running on the server
    // and transmits the file.
    public class fileTransferClient
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    // this method transfers the prescribed file to the server.
    // if the destination directory is "", it transfers the file to
    "d:\\".
    //11-21-02 Changes : This method now has a new parameter that
    references the item
    //that is being transferred in the import list.
    public static String transferFile(String srcFileName, String
    destFileName,
    String destDir, int itemID)
    if (destDir.equals(""))
    destDir = "E:\\FTP\\incoming\\";
    // get the fully qualified filename and the mere filename.
    String fqfn = srcFileName;
    String fname =
    fqfn.substring(fqfn.lastIndexOf(File.separator)+1);
    try
    //importTable importer = jbInit.getImportTable();
    // create the file to be uploaded and a connection to
    servlet.
    File fileToUpload = new File(fqfn);
    long fileSize = fileToUpload.length();
    // get last mod of this file.
    // The last mod is sent to the servlet as a header.
    long lastMod = fileToUpload.lastModified();
    String strLastMod = String.valueOf(lastMod);
    URL serverURL = new URL(webadminApplet.strServletURL);
    URLConnection serverCon = serverURL.openConnection();
    // a bunch of connection setup related things.
    serverCon.setDoInput(true);
    serverCon.setDoOutput(true);
    // Don't use a cached version of URL connection.
    serverCon.setUseCaches (false);
    serverCon.setDefaultUseCaches (false);
    // set headers and their values.
    serverCon.setRequestProperty("Content-Type",
    "application/octet-stream");
    serverCon.setRequestProperty("Content-Length",
    Long.toString(fileToUpload.length()));
    serverCon.setRequestProperty(FILENAME_HEADER, destDir +
    destFileName);
    serverCon.setRequestProperty(FILELASTMOD_HEADER, strLastMod);
    if (webadminApplet.DEBUG) System.out.println("Connection with
    FTP server established");
    // create file stream and write stream to write file data.
    FileInputStream fis = new FileInputStream(fileToUpload);
    OutputStream os = serverCon.getOutputStream();
    try
    // transfer the file in 4K chunks.
    byte[] buffer = new byte[4096];
    long byteCnt = 0;
    //long percent = 0;
    int newPercent = 0;
    int oldPercent = 0;
    while (true)
    int bytes = fis.read(buffer);
    byteCnt += bytes;
    //11-21-02 :
    //If itemID is greater than -1 this is an import file
    transfer
    //otherwise this is a header graphic file transfer.
    if (itemID > -1)
    newPercent = (int) ((double) byteCnt/ (double)
    fileSize * 100.0);
    int diff = newPercent - oldPercent;
    if (newPercent == 0 || diff >= 20)
    oldPercent = newPercent;
    jbInit.getImportTable().displayFileTransferStatus
    (itemID,
    newPercent);
    if (bytes < 0) break;
    os.write(buffer, 0, bytes);
    os.flush();
    if (webadminApplet.DEBUG) System.out.println("No of bytes
    sent: " + byteCnt);
    finally
    // close related streams.
    os.close();
    fis.close();
    if (webadminApplet.DEBUG) System.out.println("File
    Transmission complete");
    // find out what the servlet has got to say in response.
    BufferedReader reader = new BufferedReader(
    new
    InputStreamReader(serverCon.getInputStream()));
    try
    String line;
    while ((line = reader.readLine()) != null)
    if (webadminApplet.DEBUG) System.out.println(line);
    finally
    // close the reader stream from servlet.
    reader.close();
    } // end of the big try block.
    catch (Exception e)
    System.out.println("Exception during file transfer:\n" + e);
    e.printStackTrace();
    return("FTP failed. See Java Console for Errors.");
    } // end of catch block.
    return("File: " + fname + " successfully transferred.");
    } // end of method transferFile().
    } // end of class fileTransferClient
    Server side code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.net.*;
    // This servlet class acts as an FTP server to enable transfer of
    files
    // from client side.
    public class FtpServerServlet extends HttpServlet
    String ftpDir = "D:\\pub\\FTP\\";
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException,
    IOException
    doPost(req, resp);
    public void doPost(HttpServletRequest req, HttpServletResponse
    resp)
    throws ServletException,
    IOException
    // ### for now enable overwrite by default.
    boolean overwrite = true;
    // get the fileName for this transmission.
    String fileName = req.getHeader(FILENAME_HEADER);
    // also get the last mod of this file.
    String strLastMod = req.getHeader(FILELASTMOD_HEADER);
    String message = "Filename: " + fileName + " saved
    successfully.";
    int status = HttpServletResponse.SC_OK;
    System.out.println("fileName from client: " + fileName);
    // if filename is not specified, complain.
    if (fileName == null)
    message = "Filename not specified";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    else
    // open the file stream for the file about to be transferred.
    File uploadedFile = new File(fileName);
    // check if file already exists - and overwrite if necessary.
    if (uploadedFile.exists())
    if (overwrite)
    // delete the file.
    uploadedFile.delete();
    // ensure the directory is writable - and a new file may be
    created.
    if (!uploadedFile.createNewFile())
    message = "Unable to create file on server. FTP failed.";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    else
    // get the necessary streams for file creation.
    FileOutputStream fos = new FileOutputStream(uploadedFile);
    InputStream is = req.getInputStream();
    try
    // create a buffer. 4K!
    byte[] buffer = new byte[4096];
    // read from input stream and write to file stream.
    int byteCnt = 0;
    while (true)
    int bytes = is.read(buffer);
    if (bytes < 0) break;
    byteCnt += bytes;
    // System.out.println(buffer);
    fos.write(buffer, 0, bytes);
    // flush the stream.
    fos.flush();
    } // end of try block.
    finally
    is.close();
    fos.close();
    // set last mod date for this file.
    uploadedFile.setLastModified((new
    Long(strLastMod)).longValue());
    } // end of finally block.
    } // end - the new file may be created on server.
    } // end - we have a valid filename.
    // set response headers.
    resp.setContentType("text/plain");
    resp.setStatus(status);
    if (status != HttpServletResponse.SC_OK)
    getServletContext().log("ERROR: " + message);
    // get output stream.
    PrintWriter out = resp.getWriter();
    out.println(message);
    } // end of doPost().
    } // end of class FtpServerServlet

    OK - the problem you describe is definitely what's giving you grief.
    The workaround is to use a socket connection and send your own request headers, with the content length filled in. You may have to multi-part mime encode the stream on its way out as well (I'm not about that...).
    You can use the following:
    http://porsche.cis.udel.edu:8080/cis479/lectures/slides-04/slide-02.html
    on your server to get a feel for the format that the request headers need to take.
    - Kevin
    I get the out of Memory Error on the client side. I
    was told that this might be a bug in the URLConnection
    class implementation that basically it wont know the
    content length until all the data has been written to
    the output stream, so it uses an in memory buffer to
    store the data which basically causes memory issues..
    do you think there might be a workaround of any kind..
    or maybe a way that the buffer might be flushed after
    a certain size of file has been uploaded.. ?? do you
    have any ideas?

  • Passing an array as parameter from java (java controls) to stored procedure

    Hi,
    I'm using java controls (BEA Weblogic Workshop 8.1) to call a stored procedure and send an array as a parameter to the stored procedure from java. The following code below throws an exception "Fail to convert to internal representation".
    Java code
    import com.bea.control.DatabaseControl.SQLParameter;
    // Here i create the java array
    int[] javaArray={12,13,14};
    //The code below is used to create the oracle sql array for the procedure
    SQLParameter[] params = new SQLParameter[1];
    Object obj0=javaArray;
    params[0] = new SQLParameter(obj0, oracle.jdbc.OracleTypes.ARRAY, SQLParameter.IN);
    // the code below calls the testFunc method in OJDBCtrl.jcx file
    String succ= dbControl.testFunc(params);
    OJDBCtrl.jcx
    * @jc:sql statement="call CMNT_TST_PROC(?))"
    String testFunc(SQLParameter[] param);
    The stored procedure used:
    TYPE SL_tab IS TABLE OF number INDEX BY PLS_INTEGER;
    Procedure cmnt_tst_proc (cmnt_tst sl_tab);
    Procedure cmnt_tst_proc (cmnt_tst sl_tab) is
    BEGIN
    dbms_output.put_line('Hello');
    END;
    I am getting the following exception
    Failure=java.sql.SQLException: Fail to convert to internal representation: [I@438af4 [ServiceException]>
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:162)
    at oracle.jdbc.driver.DatabaseError.check_error(DatabaseError.java:861)
    at oracle.sql.ARRAY.toARRAY(ARRAY.java:210)
    at oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:7768)
    at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7449)
    at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7837)
    at oracle.jdbc.driver.OracleCallableStatement.setObject(OracleCallableStatement.java:4587)
    at weblogic.jdbc.wrapper.PreparedStatement.setObject(PreparedStatement.java:244)
    at com.bea.wlw.runtime.core.control.DatabaseControlImpl._setParameter(DatabaseControlImpl.jcs:1886)
    at com.bea.wlw.runtime.core.control.DatabaseControlImpl.getStatement_v2(DatabaseControlImpl.jcs:1732)
    at com.bea.wlw.runtime.core.control.DatabaseControlImpl.invoke(DatabaseControlImpl.jcs:2591)
    at com.bea.wlw.runtime.core.dispatcher.DispMethod.invoke(DispMethod.java:377)
    at com.bea.wlw.runtime.core.container.Invocable.invoke(Invocable.java:433)
    at com.bea.wlw.runtime.core.container.Invocable.invoke(Invocable.java:406)
    at com.bea.wlw.runtime.core.container.Invocable.invoke(Invocable.java:249)
    at com.bea.wlw.runtime.jcs.container.JcsContainer.invoke(JcsContainer.java:85)
    at com.bea.wlw.runtime.core.bean.BaseContainerBean.invokeBase(BaseContainerBean.java:224)
    at com.bea.wlw.runtime.core.bean.SLSBContainerBean.invoke(SLSBContainerBean.java:109)
    at com.bea.wlwgen.StatelessContainer_ly05hg_ELOImpl.invoke(StatelessContainer_ly05hg_ELOImpl.java:153)
    Can you please let me know, what i'm doing wrong and how i can pass an array to a procedure/function using java controls.
    Any help will be highly appreciated.
    Edited by: user12671762 on Feb 24, 2010 5:03 AM
    Edited by: user9211663 on Feb 24, 2010 9:04 PM

    Thanks Michael.
    Here's the final code that i used, this might be helpful for those who face this problem
    Java Code
    // Following code gets the connection object
    InitialContext ctx = new InitialContext();
    dataSource = (DataSource)ctx.lookup("<DataSourceName>");
    conn=dataSource.getConnection();
    // Following code is used to create the array type from java
    String query="CREATE OR REPLACE TYPE STR_ARRAY AS VARRAY(3) OF NUMBER";
    dbControl.runTypeQuery(query);
    // Following code is used to obtain the oracle sql array as SQLParameter
    ArrayDescriptor desc = ArrayDescriptor.createDescriptor("<schemaName>.STR_ARRAY", conn);
    Object[] elements = new Object[3];
    elements[0] = new Integer(12);
    elements[1] = new Integer(13);
    elements[2] = new Integer(14);
    oracle.sql.ARRAY newArray = new oracle.sql.ARRAY( desc, conn, elements);
    SQLParameter[] params = new SQLParameter[1];
    params[0] = new SQLParameter(newArray, oracle.jdbc.OracleTypes.ARRAY, SQLParameter.IN);
    String succ= dbControl.testFunc(params);

  • Writing Image files from Applet to Servlet

    How to write ImageFiles from an Applet to a Servlet?
    I draw a image on a JComponent in Applet and wanted to save the image file in the server.
    I am unable to write an Image Object to the Servlet as the BufferedImage class is not serialized.
    I tried writing the image to the Servlet output stream and tried reading the data in the servlet and writing the data to a jpg file.
    But the files is not being written as proper jpeg file.
    Any help would be great.
    Thanks,
    Sridhar.

    I get the following exception below when i try to write a Serialized object from an applet to the servlet.
    I copied the serialized class jar file to the tomcat webserver lib folder.
    The serialized class has a BufferedImage object.
    Serialized Class Code
    public class SerializedImage implements Serializable{
         private BufferedImage im = null;
         public SerializedImage() {
              super();
         public BufferedImage getSerializedObject() {
              return im;
         public void setSerializedObject((BufferedImage im) {
              this.im = im;
         private BufferedImage fromByteArray(byte[] imagebytes) {
              try {
                   if (imagebytes != null && (imagebytes.length > 0)) {
                        BufferedImage im = ImageIO.read(new ByteArrayInputStream(imagebytes));
                        return im;
                   return null;
              } catch (IOException e) {
                   throw new IllegalArgumentException(e.toString());
         private byte[] toByteArray(BufferedImage o) {
              if(o != null) {
                   BufferedImage image = (BufferedImage)o;
                   ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
                   try {
                        ImageIO.write(image, "jpg", baos);
                   } catch (IOException e) {
                        throw new IllegalStateException(e.toString());
                   byte[] b = baos.toByteArray();
                   return b;
              return new byte[0];
         private void writeObject(java.io.ObjectOutputStream out)
         throws IOException {
              byte[] b = toByteArray(im);
              out.writeInt(b.length);
              out.write(b);
         private void readObject(java.io.ObjectInputStream in)
         throws IOException, ClassNotFoundException {
              int length = in.readInt();
              byte[] b = new byte[length];
              in.read(b);
              im = fromByteArray(b);
    Exception :
    java.io.StreamCorruptedException: unexpected block data
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1288)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:18
    45)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1769)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1
    646)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1274)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:324)
    Is there any thing that i am missing or doing wrong?
    Thanks,
    Sridhar.

  • Writing to file on server from applet

    ok i know this issue has been dealt with on numerous occasions but i would like someone to explain me in details what would be the best way of doing it.
    I know that one way of doing it is having a servlet which would perform I/O and would communicate with the applet via a socket. What I don't understand is when and how does the servlet start running.
    It has to be running to be able to first accept a connection from the applet and then listen on the specified port.
    So how does the servlet start running so as to be able to communicate with the applet?
    Could you please make your answers as precise as possible.
    Thanks

    Servlets are run by servlet containesr. You must start container first (Tomcat, Jetty, Weblogic, Websphere, ...) and then it will handle running servlet. Usually it is a first http-request that instantiates servlet on-demand, but you may configure it to be instantiated at container startup. So, only you have to worry about is to put servlet on container server and it will take care of the rest.
    Simple writing to a server-side file is easier to do with PHP if you have linux/unix-based web server. Just installing a servlet container for it might be a bit overkill.

  • Passing Parameter from javascript to Servlet

    hi,
    I have 2 list boxes in my Jsp page and values for these list boxes are preloaded . These things are to be carried out using javascript onload() function.
    So now i want to pass the selected parameters from both the list boxes to servlet and have to display the corresponding resulting datas in same JSP page. if i submit the form then values selelcted by the user will reset because the form has onload() function. then i thought hidden field will solve my problem. but its giving error like nullpointer exception.
    so please tell me how to achive this.

    When you right a new Option(...) line in javascript, there are three parameters you can give:
    Option("text", "value", selected);
    How you make use of this depends on how you move from the servlet back to the JSP.
    So for example, if you are doing a response.sendRedirect in the servlet, you will either have to add a parameter back to the url you are re-directing to, or add the value to the session. (I like the session method myself... hides it from the user)
    //in servlet
      public void doGet(...)... {
        String country = request.getParameter("country");
        String state = request.getParameter("state");
        //... Do Stuff ...
        HttpSession session session = request.getSession();
        session.setAttribute("country", country);
        session.setAttribute("state", state);
        String sendTo = response.encodeRedirectURL("theForm.jsp");
        response.sendRedirect(sendTo);
      //... The JSP might look like this now...
      //Get the selected values from the session:
      <%
        String countrySelected = (String)session.getAttribute("country");
        String stateSelected = (String)session.getAttribute("state");
      %>
      <html>
      <head>
      <script type="text/javascript">
      /* Use this to store the values for states in JavaScript */
      var state2DArray;
      /* Javascript function to set up values for the states  and countries */
      function initSelects() {
        <%
          /* This is JSP scriptlet code to get the country list that we need... */
          List countries = (List)application.getAttribute("countryList");
        %>
        countrySelect = document.form.country;
        <%
          /* This is JSP scriptlet code to loop through the countries and assign
           * values as needed.  We will break out of scriptlets to print out
           * the javascript needed to assign values to the countrySelect and to
           * the state2DArray
          int countryCount = countries.size();
        %>
        state2DArray=new Array(<%=countryCount+1%>);
          state2DArray[0] = new Array(1);
          state2DArray[0][0]="--Select A State--";
        <%
          for (int co = 1; co <= countryCount; co++) {
            Country country = (Country)countries.get(co-1);
            List stateList = country.getStates();
            int stateCount = stateList.size();
        %>
        //Now we add a true/false if the country should be selected...
        countrySelect.options[<%=co%>] = new Option("<%=country.getName()%>","<%=country.getId()%>",
                                                    <%= (country.getId() == countrySelected)%>);
        state2DArray[<%=co%>] = new Array(<%=stateCount+1%>);
        state2DArray[<%=co%>][0] = "--Select A State--";
        <%
            for (int st = 1; st <= stateCount; st++) {
              String stateName = (String)stateList.get(st-1);
        %>
        state2DArray[<%=co%>][<%=st%>] = "<%=stateName%>";
        //We are going to call the fillInStates now at the end of initSelects so the initial
        //values are passed on to the states...
        fillInStates(countrySelect);
        <%
        %>
      function fillInStates(countrySelect) {
        selectedCountry = countrySelect.selectedIndex;
        stateCount = state2DArray[selectedCountry].length;
        stateSelect = document.form.state;
        stateSelect.options.length = 0;
        for (state = 0; state < stateCount; state++) {
          //Again add true/false if it should be selected...
          stateSelect.options[state] = new Option(state2DArray[selectedCountry][state], state2DArray[selectedCountry][state],
                                                  <%= (stateSelected == state2DArray[selectedCountry][state]) %>);
    </script>
      </head>
      <body onload="initSelects()">
      <form name="form" id="form" action="#" method="get">
        <select name="country" id="country" onchange="fillInStates(this);">
          <option value="">--Select A Country--</option>
        </select>
        <select name="state" id="state">
          <option value="">--Select a State--</option>
        </select>
      </form>
      </body>
    </html>

  • Sending different types of data from applet to servlet

    Hi,
    I am writing an applet that uploads a file to a servlet. I can send the file to the servlet just fine.
    Applet Side
    1. open a URLConnection
    2. open a DataOutputStream
    3. write the file to the DataOutputStream
    Servlet Side:
    1. open a ServletInputStream from the HttpServletRequest
    2. write the bytes to a file
    This is all fine.
    However, I need to upload the filename (a String) with the file. How do I do this? I can't send the filename over as a String from the applet using the same DataOutputStream. right? This would corrupt the file that i am sending as the servlet wouldn't know that the difference between the filename and the actual contents of the file.
    Is there some property I can set in the urlconnection that gets passed to the request variable? i.e. URLConnection.setProperty ("filename", foo.txt) and then on the servlet side do this: String filename = eq.getProperty ("filename")
    Thank you for the help

    If all the additional data you want to send to server are textual or numaric data about the file (which is in the body of the request)
    Use those information as additional http headers.
    And read those header information from the servlet request object at the server side
    ex:-
    URL u = new URL("your url");
    HttpURLConnection c = (HttpURLConnection)u.openConnection();
    c.addRequestProperty("x-application-file-name","name of the file");
    c.addRequestProperty("x-application-file-size","size of the file");
    //then open the stream and write the data to the request body
    //             At server side         //
    String name = request.getHeader("x-application-file-name");
    long size= Long.parseLong(request.getHeader("x-application-file-size"));

  • Request parameter from jsp in servlet

    i need to know what is the complete code in servlet
    to get parameters from the fragment code shown below in a jsp file.
    Neddng it urgent, thank in advance, take care.
    <form method="get">
    field: <input type="text" name="field">
    <br>
    tablename: <input type="text" name = "tablename"><br>
    <jsp:forward page="hello.jsp">
    <jsp:param name ="field" value="field"/>
    <jsp:param name = "tablename" value="tablename"/>
    </jsp:forward>
    <br><br>
    <input type="submit" value="Submit">
    </form>

    If I understand anything...
    TO let it have some sense:
    <form method="get">
    field: <input type="text" name="field">
    <br>
    tablename: <input type="text" name = "tablename"><br>
    <% if(request.getParameter("field")!=null) { %>
    <jsp:forward page="hello.jsp">
    <jsp:param name ="field" value="field"/>
    <jsp:param name = "tablename" value="tablename"/>
    </jsp:forward>
    <%}%>
    <br><br>
    <input type="submit" value="Submit">
    </form>
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    * @author  akulinsk
    * @version
    public class NewServlet extends HttpServlet {
        /** Initializes the servlet.
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        /** Destroys the servlet.
        public void destroy() {
        /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            String field = request.getParameter("field");
            String tablename = request.getParameter("tablename");
            //DO SOMETHING HERE
            out.close();
        /** Handles the HTTP <code>GET</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Returns a short description of the servlet.
        public String getServletInfo() {
            return "Short description";
    }

  • How to transfer the http request from applet to servlet/jsp

    I use the JTree component to create a navigation of a website,but i don't
    know how to connect the tree's nodes with the jsp/servlet.
    I mean how to transfer the http request from the applet to a jsp.
    I use the "<frameset>" mark which will divide the web browse into 2 blocks.
    The left side is Applet,and the right side is the linked jsp page.
    what I say is as the weblogic console layout.
    who can help me!!!
    Thank You!

    I use the JTree component to create a navigation of a website,but i don't
    know how to connect the tree's nodes with the jsp/servlet.
    I mean how to transfer the http request from the applet to a jsp.
    I use the "<frameset>" mark which will divide the web browse into 2 blocks.
    The left side is Applet,and the right side is the linked jsp page.
    what I say is as the weblogic console layout.
    who can help me!!!
    Thank You!

  • Passing parameter to Applet Dynamically

    Hi All,
    How can i pass the parameter to applet at the runtime?
    I want to play a video file. So 'm using one applet(I got this from JMF Documentation).
    Here is the Applet._
    import java.applet.Applet;
    import java.awt.*;
    import java.io.File;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.io.IOException;
    import javax.media.*;
    import javax.swing.JOptionPane;
    public class TypicalPlayerApplet extends Applet implements ControllerListener
    // media player
    Player player = null;
    String mediaFile = null;
    // component in which video is playing
    Component visualComponent = null;
    // controls gain, position, start, stop
    Component controlComponent = null;
    // displays progress during download
    Component progressBar = null;
    * Read the applet file parameter and create the media
    * player.
    public void init()
    setLayout(new BorderLayout());
    // input file name from html param
    //String mediaFile = null;
    // URL for our media file
    URL url = null;
    // URL for doc containing applet
    URL codeBase = getDocumentBase();
    // Get the media filename info.
    // The applet tag should contain the path to the
    // source media file, relative to the html page.
    if ((mediaFile = getParameter("FILE")) == null)
    Fatal("Invalid media file parameter");
    try
    // Create an url from the file name and the url to the
    // document containing this applet.
    if ((url = ((new File(mediaFile)).toURI()).toURL()) == null)
    Fatal("Can't build URL for " + mediaFile);
    // Create an instance of a player for this media
    if ((player = Manager.createPlayer(url)) == null)
    Fatal("Could not create player for "+url);
    // Add ourselves as a listener for player's events
    player.addControllerListener(this);
    catch (NoPlayerException ex)
    JOptionPane.showMessageDialog(null, "Error "+ex.getMessage());
    catch (MalformedURLException u)
    Fatal("Invalid media file URL!");
    catch(IOException i)
    Fatal("IO exception creating player for "+url);
    * Start media file playback. This function is called the
    * first time that the Applet runs and every
    * time the user re-enters the page.
    public void start()
    // Call start() to prefetch and start the player.
    if (player != null) player.start();
    * Stop media file playback and release resources before
    * leaving the page.
    public void stop()
    if (player != null)
    player.stop();
    player.deallocate();
    * This controllerUpdate function must be defined in order
    * to implement a ControllerListener interface. This
    * function will be called whenever there is a media event.
    public synchronized void controllerUpdate(ControllerEvent event)
    // If we're getting messages from a dead player,
    // just leave
    if (player == null) return;
    // When the player is Realized, get the visual
    // and control components and add them to the Applet
    if (event instanceof RealizeCompleteEvent)
    if ((visualComponent = player.getVisualComponent()) != null)
    add("Center", visualComponent);
    if ((controlComponent = player.getControlPanelComponent()) != null)
    add("South",controlComponent);
    // force the applet to draw the components
    validate();
    else if (event instanceof CachingControlEvent)
    // Put a progress bar up when downloading starts,
    // take it down when downloading ends.
    CachingControlEvent e = (CachingControlEvent) event;
    CachingControl cc = e.getCachingControl();
    long cc_progress = e.getContentProgress();
    long cc_length = cc.getContentLength();
    // Add the bar if not already there ...
    if (progressBar == null)
    if ((progressBar = cc.getProgressBarComponent()) != null)
    add("North", progressBar);
    validate();
    // Remove bar when finished ownloading
    if (progressBar != null)
    if (cc_progress == cc_length)
    remove (progressBar);
    progressBar = null;
    validate();
    else if (event instanceof EndOfMediaEvent)
    // We've reached the end of the media; rewind and
    // start over
    player.setMediaTime(new Time(0));
    player.start();
    else if (event instanceof ControllerErrorEvent)
    // Tell TypicalPlayerApplet.start() to call it a day
    player = null;
    Fatal (((ControllerErrorEvent)event).getMessage());
    void Fatal (String s)
    // Applications will make various choices about what
    // to do here. We print a message and then exit
    System.err.println("FATAL ERROR: " + s);
    throw new Error(s); // Invoke the uncaught exception
    // handler System.exit() is another
    // choice
    Following is my HTML Code,_
    <applet id="TypicalPlayerApplet" name="TypicalPlayerApplet" code="TypicalPlayerApplet.class" codebase="app" width=320 height=300>
    <param name=file id="param1" value="c:\\avi\\cineloop1.avi" />
    </applet>
    What my question is how can i pass this location "c:\\avi\\cineloop1.avi" at the runtime. I am passing the cineloop location along with the URL. Now i want to pass this location which is taken from the URL, to the Applet.
    How can i achieve this. Will some one help me out.
    Thanks and regards
    Chennaibee.

    Thanks winj,
    I tried to pass the cine loop filename via java script on page load event.
    function assignit()
    var filename='c:\\avi\\loop3.avi';
    var myapplet = document.getElementById('TypicalPlayerApplet');
    myapplet.mediaFile=filename;
    And in the page load event i called this JS.
    *<body onload='assignit();'>*
    It's passing the file name after the applet getting started.
    How can i pass the file name before the applet getting starts.
    Is it possible to call this Java Script during the page initialization.
    Regards
    Chennaibee.

Maybe you are looking for