如何将struts 2中的照片上传到我的public_html目录而不是我的tomcat目录中?
上传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_html/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;
}
When uploading 1-6969875-2644-t.jpg
, the image is uploaded to/home/xrcwrn/jvm/apache-tomcat-6.0.14/domains/xyz.com/ROOT/img/1-6969875-2644-t.jpg
properly.
But I actually want to upload this image into the /home/xrcwrn/public_html/img
folder.
I am using this code in 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要使用 ServletContext#getRealPath()。您不想将上传的文件写入那里。每当您重新部署 Web 应用程序甚至重新启动服务器时,它们都会丢失。
替换
为
如果要使其可配置,请考虑将其提供为系统属性或属性文件设置。
Don't use
ServletContext#getRealPath()
. You don't want to write uploaded files to there. They will get lost whenever you redeploy the webapp or even when you restart the server.Replace
by
If you want to make this configureable, consider providing it as a system property or a properties file setting.