2

I have a fileupload servlet in java. And i want to set path to upload folder, to it waork on any server. I say:

 File disk = new File("/myportlet/upload/"+item.getName());
 item.write(disk);

But nothing saved. When i use absolute path to upload folder all work fine.
So how to set path to upload folder in server?

11
  • 3
    You should be aware that you violate the servlet spec by wanting to write inside the server. Commented Dec 19, 2012 at 12:15
  • u can try with the getContextPath() Commented Dec 19, 2012 at 12:15
  • 1
    Look at the path. If the applet runs on linux, the first slash would set you to the root. Try ./myportlet/upload/ Commented Dec 19, 2012 at 12:18
  • This probably fails due to / being interpreted as "root of filesystem" in the File() constructor. As Thorbjørn writes above, you're violating the spec if you actually write to the server area. I'd suggest using a welldefined space on the filesystem for these files instead. Commented Dec 19, 2012 at 12:18
  • 1
    @looper you are not guaranteed that the current working directory is set to anything useful to you. Commented Dec 19, 2012 at 12:21

2 Answers 2

2

The leading "/" at the new File() constructor refers to the root of the file system. The file will be written into a directory named /myportlet/upload, in your code.

As the comments implied, writing into appserver-internal directories violates the spec and is generally a terrible idea - I honestly can't think of one proper use for doing so. What you want to do is to read the target path from a parameter - for example, a servlet's initialization parameter or a context initialization parameter - and use that.

Sign up to request clarification or add additional context in comments.

2 Comments

servlet's initialization parameter or a context initialization parameter - and use that. Can you give a example? Im not good in java.
Google is your best friend here... :-) see this for example: tutorials.jenkov.com/java-servlets/web-xml.html#initParams
2

I used the below snippet. It worked fine in windows server.

File f=new File("sample.xls");
        f.createNewFile();
        FileOutputStream fos=null;
        if(f != null){
            fos=new FileOutputStream(f);
            fos.write(b);
            fos.flush();
            fos.close();
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.