Linux File Upload - Servlet

Hello,

I have a servlet which upload multiple files. Its working fine with localhost:8080, but when I trying to execute this servlet on linux box I dont see any error either seems like it upload. But I dont see any file on linux. Do I need to write anything speical in code ???

File tosave=new File(getServletContext().getRealPath("/mpg/d1/files/"),cfile.getName());

Thanks for your time !!!
princehyderabadAsked:
Who is Participating?
 
aozarovCommented:
If you want to write under root "/mpg/d1/files/" then don't call getRealPath which will prepend the context path.
Just do :
File tosave=new File("/mpg/d1/files/",cfile.getName());

You need to make sure that the web container has write permissions there.
To change permissions on your file system you need to run from the command line (shell):
chmod a+w /mpg/d1/files
This will make that folder writable to all.
0
 
aozarovCommented:
is your servlet sending this file "/mpg/d1/files/<cfile.filename>" to the client or is it going to write to this file?
Can you provide the logic that deals with the tosave file?
0
 
princehyderabadAuthor Commented:
I'm accepting the User Form to Upload the files on Server machine. So bascially its writing on server machine.
On http://localhost:8080 my servlet taking this path "/mpg/d1/files/" plus <cfile.filename> and writing on local machine.
Hope U got now !!
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
aozarovCommented:
Does the web container have write permissions to that specific folder?
0
 
princehyderabadAuthor Commented:
Yes
0
 
aozarovCommented:
Can you provide the logic that deals with the tosave file?
0
 
princehyderabadAuthor Commented:
File tosave=new File(getServletContext().getRealPath("/mpg/d1/files/"),cfile.getName());
item.write(tosave);

Its very simple as I already mention logic is uploading file from client to server machine.

tosave get the ServletContext plus directory path and file name and writes(upload) on server machine.
0
 
aozarovCommented:
I was expecting to the item.write(...) logic.
0
 
princehyderabadAuthor Commented:
oops sorry I should hv metioned before.  
0
 
princehyderabadAuthor Commented:
Seems like I got the error:

 Error : /mpg/d1/activate/webapps/myApp/mpg/d1/files/net.exe (Permission denied)
     
Its following my Root Context to upload. Let me show U directorys:

<mpg>
         <d1>
                  <files>
                 <activate>
                               <webapps>
                                                <myApp>
                                                 (All my folders n files)

How can I make file write on  /mpg/d1/files/

0
 
aozarovCommented:
chmod a+w /mpg/d1/activate/webapps/myApp/mpg/d1/files
or instead of a (all) set the permission to the group as long as the web-container is part of that group.
0
 
princehyderabadAuthor Commented:
can you write complete line code please.

you mean this getRealPath("/mpg/d1/files/") shoud be replaced with getRealPath(" chmod a+w /mpg/d1/files/")
I want it to write to /mpg/d1/files under the root. But not under my <myApp>
0
 
princehyderabadAuthor Commented:
Excellent it worked.

Thanks a Lot !!!
0
 
aozarovCommented:
:-)
0
 
princehyderabadAuthor Commented:
Any idea how to make director on Linux machine if it doesnt exits.

I mean if wanna write files to "/mpg/d1/files/exe/" what if this doesnt exit on. how sh I make or give command to make directory.
0
 
princehyderabadAuthor Commented:
rpath = rs.getString(1):

String a = "/mpg/d1/am-files/"+rpath;
File tosave=new File(a,cfile.getName());

/mpg/d1/am-files/ (This directory path is present on linxu machine)
now my programs need to know if
/mpg/d1/am-files/rpath does exits, if so follow next line if not wht is the command to make "rpath" folder under /mpg/d1/am-files/
0
 
aozarovCommented:
you can call http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#mkdirs() which will
make the directories for you (or do nothing if they already exists).
e.g.
String a = "/mpg/d1/am-files/"+rpath;
File folder = new File(a);
folder.mkdirs();
File tosave=new File(folder,cfile.getName());
...
0
 
princehyderabadAuthor Commented:
Thanks it worked :o)
0
 
aozarovCommented:
:-)
0
 
princehyderabadAuthor Commented:
Aozarov, Need your help again !!

I dont know what happened somethign wired on my application. Till few days back my code and everything was working perfect but today something wired.

I guess this below line is suppose to puck the file name and write correct ?

File tosave=new File(a,cfile.getName());

2 things happening:
1. Instead of picking file 'abc.exe' it is picking 'c:/abc.exe'
2. Not writing on server proporly because there is no such file 'c:/abc.exe'

How do I nkow it is picking 'c:/abc.exe'  ?
Before writing to server I'm saving filename etc., on DB. and When I checked DB fileds. File Name I found was 'c:/abc.exe'  instead of 'abc.exe'

Hope you got my idea
0
 
aozarovCommented:
>> File tosave=new File(a,cfile.getName());
Did you printout "cfile.getName()" -> my guess it should be abc.exe
Also printout the value of a -> my guess it is "c:/" for some reason
0
 
princehyderabadAuthor Commented:
1st I'm writing into DB and then I'm writing(uploading only files) to server

This is the code to write to DB all fields including filenames:
=======================================
 File cfile=new File(item.getName());
                       // String  sizefile = new String (item.getSize());

                        cs1.setString(1,"save");
                                   cs1.setString(2,"");
                        cs1.setString(3,(String) map.get("family"));
                        cs1.setString(4,(String) map.get("product"));
                        cs1.setString(5,(String) map.get("type"));
                        cs1.setString(6,(String) map.get("ver"));
                        cs1.setString(7,(String) map.get("lang"));
                        cs1.setString(8,(String) map.get("container"));
                        cs1.setString(9,cfile.getName());    //HERE IS THE FILE NAME
                        int index = cfile.getName().lastIndexOf(".");
                        if (index >= 0)  {      ext = cfile.getName().substring(index + 1);  }
                        cs1.setString(10,ext);
                        cs1.setString(11,String.valueOf(item.getSize()));
                        cs1.setString(12,"");
                        cs1.setString(13,(String) map.get("containerdesc"));

                        cs1.executeQuery();
=============================================


This is the code to write to server :

==============================================
 File cfile=new File(item2.getName());
                                 File path = new File("/mpg/downloads/"+rpath);
                                    if (!path.exists())
                                    {
                                       path.mkdirs();
                                    }

                              File tosave=new File(path,cfile.getName());
                            item2.write(tosave);
                            fileMap.put(cfile.getName(), item2);
===============================================
0
 
aozarovCommented:
Strange, it looks like
File cfile=new File(item.getName());
cfile.getName() returns the path instead of just the filename.
Can you validate it and printout:

File cfile=new File(item.getName());
System.out.println("item.getName() -> " + item.getName());
System.out.println("cFile.getName() -> " + cFile.getName());
0
 
princehyderabadAuthor Commented:
Okay really really something wired now:

I tried printout on localhost:8080  and I got correct answer: And in DB filename 'db1.mdb'  saved correctly.
Also it is writing (upload) on local machine.

item.getName() -> C:\db1.mdb
cFile.getName() -> db1.mdb

NOW THE PROBLEM, WHEN I TEST THIS ON APACHE-TOMCAT4.0 IT IS NOT DOING THE SAME.
In DB the file name I got is 'c:/db1.mdb' and it is not even writing(upload) to server its bcoz it trying to find 'c:/db1.mdb' whole as file.

Please help on this issue.
I'm surprised to know it worked last week but now hmm...
0
 
aozarovCommented:
>> NOW THE PROBLEM, WHEN I TEST THIS ON APACHE-TOMCAT4.0 IT IS NOT DOING THE SAME.
What is the output of:
System.out.println("item.getName() -> " + item.getName());
System.out.println("cFile.getName() -> " + cFile.getName());

On that environment?
0
 
princehyderabadAuthor Commented:
Ok it is not at all printing it. Seems like it is not going in that else part..... Let me paste u my code...
0
 
princehyderabadAuthor Commented:
try {

                Pool con_pool=Pool.getInstance();
                Connection connection =con_pool.get_Connection();

                 DiskFileUpload upload = new DiskFileUpload();
                 List items = upload.parseRequest(req);
                 Iterator iter = items.iterator();
                String rpath = null;
                Map map = new HashMap();
                String ext = null;
                 while (iter.hasNext()) {

                                FileItem item = (FileItem) iter.next();
                                if (item.isFormField())
                                    {
                                        String name = item.getFieldName();
                                        String value = item.getString().trim();
                                        map.put(name,value);
                                        System.out.println("Name:"+name+ " Value:" +value+":End");
                                    }
                                 else
                                        {
                                        System.out.println("Operating on Files.....");

                        String storedProcCall1 = "{call apMaintFObjects(?,?)}";
                       CallableStatement cs1 = connection.prepareCall(storedProcCall1);


                        File cfile=new File(item.getName());

                        System.out.println("item.getName() -> " + item.getName());                    
                         System.out.println("cFile.getName() -> " + cfile.getName());

                        cs1.setString(1,cfile.getName());
                        cs1.setString(2,(String) map.get("containerdesc"));

                        cs1.executeQuery();
                                }       // END Of else

                   
                 }
            Iterator iter2 = items.iterator();                      
           Map fileMap = new HashMap();
            while (iter2.hasNext()) {
            FileItem item2 = (FileItem) iter2.next();
            if (item2.isFormField())
            {
                 System.out.println("Operating on 2nd WHILE if condition...");
            }
             else
            {
                //upload file
                System.out.println("Operating on 2nd WHILE else condition...");
                File cfile=new File(item2.getName());
                System.out.println("item2.getName() -> " + item2.getName());
                                 File path = new File("/mpg/downloads/"+rpath);                                  
                              System.out.println("Before Uploading: cFile.getName() -> " + cfile.getName());
                              File tosave=new File(path,cfile.getName());
                            item2.write(tosave);
                            fileMap.put(cfile.getName(), item2);
            }
            }//end of while
       System.out.println("Setting BEAN ... ");
       MyBean bean = new MyBean();
       bean.setFileMap(fileMap);
       req.setAttribute("mybean", bean);
       System.out.println("Done on Setting Bean");

        System.out.println("Redirecting...");
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/versionsuccessful.jsp");
        rd.forward(req, res);
0
 
aozarovCommented:
princehyderabad,
I need to go home now. I will be able to look at it in about 2 hours.
In the mean time can you check serveral things...
1) Can you validate that it goes to the other part of the else. So you should see those outputs:
System.out.println("Name:"+name+ " Value:" +value+":End");
and
System.out.println("Operating on 2nd WHILE if condition..."); [ you might want to printout item2.getFieldName() as well]
2) Can you try to acces the remote Tomcat instance directly (not thru apache) and see if it is working.
    I want to see if Apache change the form encoding type for some reason. (it is probably listening on port 8080)
3) Put as many debug statement in this section and paste here the output (so I can match the flow with the code)
0
 
princehyderabadAuthor Commented:
Okay everything is going as per program logic.  MY code 1st while loop calling if statement then going to else until 1st while end. Same for 2nd while loop.
Everything on console getting print as code.

This is the value I'm gettging on my 'Test Server' wich uses Tomcat4.0

item.getName() -> C:\Documents and Settings\Desktop\projectweb1.gif
cFile.getName() -> C:\Documents and Settings\Desktop\projectweb1.gif


The exact same code on my localhost:8080 machine which uses Tomcat5.0

item.getName() -> C:\Documents and Settings\Desktop\projectweb1.gif
cFile.getName() -> projectweb1.gif

Does Tomcat version makes diff ? But how come it was working last week on both 4.0 and 5.0 perfectly ?
0
 
aozarovCommented:
>> Everything on console getting print as code.
So why it didn't print it before? "Ok it is not at all printing it. Seems like it is not going in that else part..."

>> Does Tomcat version makes diff ? But how come it was working last week on both 4.0 and 5.0 perfectly ?
I don't think this is Tomcat issue as cFile (which is produce the wrong value for getName()) is part of the Java SDK (java.io.File)
Can you try to run this program on your 'Test Server' machine and tell me the results:
public class Test
{
      public static void main(String st[])
      {
            java.io.File file1 = new java.io.File("C:\\Documents and Settings\\Desktop\\projectweb1.gif");
            java.io.File file2 = new java.io.File("C:\\Desktop\\projectweb2.gif");
            System.out.println(file1.getName());
            System.out.println(file2.getName());
      }
}
0
 
princehyderabadAuthor Commented:
This is the OUTput on 'Test Server' machine:

C:\Documents and Settings\Desktop\projectweb1.gif
C:\Desktop\projectweb2.gif

And also I tested same java class on my local machine and the output I got is:

projectweb1.gif
projectweb2.gif


0
 
princehyderabadAuthor Commented:
0
 
aozarovCommented:
That is pretty strange.
Try to replace
C:\\Documents and Settings\\Desktop\\projectweb1.gif with C:/Documents and Settings/Desktop/projectweb1.gif
and
C:\\Desktop\\projectweb2.gif" with C:/Desktop/projectweb2.gif
and see if there is any change
0
 
princehyderabadAuthor Commented:
Okay this time I got identical result on both machines.

projectweb1.gif
projectweb2.gif
0
 
aozarovCommented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.