简体   繁体   English

将文件上载到服务器会抛出未找到文件或目录的异常

[英]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 upload_path = .. / .. / .. / upload

Make sure you also create all the parent directories on the path to upload_path : 确保您还在upload_path的路径上创建了所有父目录:

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

Note the use of mkdirs() instead of mkdir() . 注意使用mkdirs()而不是mkdir() mkdir() will fail, if the parent structure does not exist. 如果父结构不存在,则mkdir()将失败。 mkdirs() will also try to create the required parent directories. mkdirs()还将尝试创建所需的父目录。

You should also check for the return value, both methods will return false if the directory could not be created. 您还应该检查返回值,如果无法创建目录,则这两种方法都将返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM