Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Linux File Upload - Servlet

Posted on 2005-04-13
35
Medium Priority
?
698 Views
Last Modified: 2013-11-24
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 !!!
0
Comment
Question by:princehyderabad
  • 19
  • 16
35 Comments
 
LVL 15

Expert Comment

by:aozarov
ID: 13778495
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
 

Author Comment

by:princehyderabad
ID: 13778843
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13781010
Does the web container have write permissions to that specific folder?
0
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!

 

Author Comment

by:princehyderabad
ID: 13784305
Yes
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13784500
Can you provide the logic that deals with the tosave file?
0
 

Author Comment

by:princehyderabad
ID: 13784915
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13784945
I was expecting to the item.write(...) logic.
0
 

Author Comment

by:princehyderabad
ID: 13785058
oops sorry I should hv metioned before.  
0
 

Author Comment

by:princehyderabad
ID: 13785378
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13785441
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
 

Author Comment

by:princehyderabad
ID: 13785506
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
 
LVL 15

Accepted Solution

by:
aozarov earned 200 total points
ID: 13785629
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
 

Author Comment

by:princehyderabad
ID: 13786263
Excellent it worked.

Thanks a Lot !!!
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13786507
:-)
0
 

Author Comment

by:princehyderabad
ID: 13819815
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
 

Author Comment

by:princehyderabad
ID: 13819832
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13820792
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
 

Author Comment

by:princehyderabad
ID: 13820842
Thanks it worked :o)
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13820852
:-)
0
 

Author Comment

by:princehyderabad
ID: 13931074
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13931099
>> 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
 

Author Comment

by:princehyderabad
ID: 13931222
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13931440
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
 

Author Comment

by:princehyderabad
ID: 13931848
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13931864
>> 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
 

Author Comment

by:princehyderabad
ID: 13931944
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
 

Author Comment

by:princehyderabad
ID: 13931976
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13932018
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
 

Author Comment

by:princehyderabad
ID: 13932177
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13932638
>> 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
 

Author Comment

by:princehyderabad
ID: 13937978
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13938381
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
 

Author Comment

by:princehyderabad
ID: 13938458
Okay this time I got identical result on both machines.

projectweb1.gif
projectweb2.gif
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13938473
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

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

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses
Course of the Month14 days, 13 hours left to enroll

578 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