我正在运行Eclipse Java EE和tomcat来运行我的webapp。我使用以下代码将图像文件存储到upload / images / profilepics目录:
public String uploadPhoto() {
try {
//get path to upload photo
String filePath = servletRequest.getSession().
getServletContext().getRealPath("/uploads/profilepics");
System.out.println("Server path:" + filePath);
//creating unique picture name
Map sess = (Map) ActionContext.getContext().get("session");
Integer uid = (Integer) sess.get("uid");
String profilePictureName = uid + "-" +
MyUtilityFunctions.createVerificationUrl() + this.userImageFileName;
//update user record
//tobe done
String imgUrl = filePath + profilePictureName;
ViewProfileModel pofilePictureUpdate = new ViewProfileModel();
pofilePictureUpdate.updateUserPhotoUrl(imgUrl, uid);
//create new File with new path and name
File fileToCreate = new File(filePath, profilePictureName);
//copy file to given location and with given name
FileUtils.copyFile(this.userImage, fileToCreate);
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
打印filePath后,得到以下结果:
服务器路径:/home/bril/webspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/picvik/uploads/profilepics
现在的问题是,我无法获取图片,或者如果我向<img src="">
提供相同的网址,则无法显示任何内容。
请纠正我做错的地方。
答案 0 :(得分:1)
有建议:
有很多原因,你不应该以这种方式保存用户图像,就像在另一个问题中提到的@DaveNewton一样。那里 是一些帮助您做出决定的帖子:
我个人的意见是将它们保存到数据库中,因为你不想要 让你的用户丢失他们的图像。
回到你的问题,有不同的方法:
<img src="/uploads/profilepics/<s:property
value='profilePictureName'/>"
JSP:
<img src="
<s:url var="profilePic" action="customer-image-action">
<s:param name="uid" value="%{uid}"/>
</s:url>
" alt="kunden logo" />
动作:
public String execute() throws Exception {
// filename = somehow(uid);
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
imgPath = request.getSession().getServletContext().getRealPath("/uploads/profilepics/")+filename;
log.debug("context-path: " + imgPath);
try {
inputStream = FileUtils.openInputStream(new File(imgPath));
} catch (IOException e) {
log.error(e.getCause(), e);
}
return SUCCESS;
}