Servlets 如何将struts 2中的照片上传到公共html目录而不是tomcat';s目录?
上载Servlets 如何将struts 2中的照片上传到公共html目录而不是tomcat';s目录?,servlets,file-upload,save,Servlets,File Upload,Save,上载1-6969875-2644-t.jpg时,图像将上载到 /home/xrcwrn/jvm/apache-tomcat-6.0.14/domains/xyz.com/ROOT/img/1-6969875-2644-t.jpg正确 但实际上我想把这个图像上传到/home/xrcwrn/public\uhtml/img文件夹中 我在Struts 2中使用了以下代码: public String execute() { try { ServletContext servl
1-6969875-2644-t.jpg
时,图像将上载到
/home/xrcwrn/jvm/apache-tomcat-6.0.14/domains/xyz.com/ROOT/img/1-6969875-2644-t.jpg
正确
但实际上我想把这个图像上传到/home/xrcwrn/public\uhtml/img
文件夹中
我在Struts 2中使用了以下代码:
public String execute() {
try {
ServletContext servletContext = ServletActionContext.getServletContext();
String path =servletContext.getRealPath("/img");
System.out.println("Server path:" + path);
String filePath = servletContext.getRealPath(path);
File uploadDir = new File(filePath);
String relPath = uploadDir.getAbsolutePath();
//if the folder does not exits, creating it
if (uploadDir.exists() == false) {
uploadDir.mkdirs();
}
File fileToCreate = new File(path, this.userImageFileName);
FileUtils.copyFile(this.userImage, fileToCreate);
String pt = path + "/" + getUserImageFileName();
System.out.println("image path is :" + pt);
setImagePath(pt);
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
System.out.println(" **************inside image upload***********");
return SUCCESS;
}
不要使用
ServletContext#getRealPath()
。你不想把上传的文件写到那里。无论何时重新部署webapp,甚至重新启动服务器,它们都会丢失
替换
String path =servletContext.getRealPath("/img");
System.out.println("Server path:" + path);
String filePath = servletContext.getRealPath(path);
借
如果您想使其可配置,请考虑将其作为系统属性或属性文件设置提供。
String filePath = "/home/xrcwrn/public_html/img";