2014-05-04 46 views
1

我有使用tomcat的 ..this是我的目录结构中的两个web项目上传文件..创建文件夹,使用的servlet

webapps 
--project1 
    --WEB-INF 
--project2 
    --WEB-INF 

我使用commons-fileupload..this是部分我在代码servlet的在PROJECT1

String fileName = item.getName();  
String root = getServletContext().getRealPath("/"); 
File path = new File(root + "/uploads"); 

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

File uploadedFile = new File(path + File.separator + fileName); 
item.write(uploadedFile); 

这将在“PROJECT1”创建“上传”文件夹,但我想在“web应用”打造“上传”文件夹,因为我不想“上传”文件夹不见了,当我取消部署“PROJECT1” ..

我已经尝试String root = System.getProperty("catalina.base");但不会工作。

谁能帮我...在此先感谢

+0

为什么不在你的服务器的另一个路径中创建'upload'文件夹,而是给所有t他允许tomcat用户读/写文件到该文件夹​​? –

+0

@LuiggiMendoza你可以用代码解释..实际上,我已经尝试在webapps中手动创建'upload'文件夹并使用 File uploadedFile = new File(“http:// localhost/upload /”+ fileName); item.write(uploadedFile); 但不工作 – nat

回答

1

首先,在Tomcat的安装文件夹以外的服务器的文件夹,例如/opt/myuser/files/upload。然后,在属性文件或web.xml中将此路径配置为Servlet init配置,以使其可用于您拥有的任何Web应用程序。

如果使用属性文件:

file.upload.path = /opt/myuser/files/upload 

如果web.xml中:

<servlet> 
    <servlet-name>MyServlet</servlet-name> 
    <servlet-class>your.package.MyServlet</servlet-class> 
    <init-param> 
     <param-name>FILE_UPLOAD_PATH</param-name> 
     <param-value>/opt/myuser/files/upload</param-value> 
    </init-param> 
</servlet> 

或者,如果你使用的Servlet 3.0规范,您可以配置的初始化参数使用@WebInitParam注释:

@WebServlet(name="MyServlet", urlPatterns = {"/MyServlet"}, 
    initParams = { 
     @WebInitParam(name = "FILE_UPLOAD_PATH", value = "/opt/myuser/files/upload") 
    }) 
public class MyServlet extends HttpServlet { 
    private String fileUploadPath; 
    public void init(ServletConfig config) { 
     fileUploadPath = config.getInitParameter("FILE_UPLOAD_PATH"); 
    } 
    //use fileUploadPath accordingly 

    public void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException) { 
     String fileName = ...; //retrieve it as you're doing it now 
     //using File(String parent, String name) constructor 
     //leave the JDK resolve the paths for you 
     File uploadedFile = new File(fileUploadPath, fileName); 
     //complete your work here... 
    } 
} 
+0

谢谢..这是工作 – nat

+0

不客气。 –