Maclean Pinto
Maclean Pinto

Reputation: 1135

Uploading file to server throws file or directory not found exception

Below is the code i have used to upload a file to the server. But the code throws a exception directory or file not found..

                ResourceBundle rs_mail = ResourceBundle.getBundle("mail");
                String upload_path = rs_mail.getString("upload_path");
                File file = null;
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                Iterator i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    File uploadDir = new File(upload_path);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdir();
                    }
                  file = new File(upload_path + file.separator + fi.getName());

                    fi.write(file);
                }

Can any one point out the reason for the exception..

Contents of the property file

upload_path=../../../upload

Upvotes: 0

Views: 444

Answers (1)

Udo Klimaschewski
Udo Klimaschewski

Reputation: 5315

Make sure you also create all the parent directories on the path to upload_path:

if (!uploadDir.exists()) {
   uploadDir.mkdirs();
}

Note the use of mkdirs() instead of mkdir(). mkdir() will fail, if the parent structure does not exist. mkdirs() will also try to create the required parent directories.

You should also check for the return value, both methods will return false if the directory could not be created.

Upvotes: 1

Related Questions