您的位置:首页 > 数据库

头像图片显示---数据库中保存路径 图片上传到工作目录下

2013-03-14 15:56 711 查看
上传的头像图片以 当前用户id为名 id.jpg..........

读取图片src=”上传路径/id.jpg“

开发环境下,上传图片到eclipse的workspace下,图片才可以显示,所有图片上传路径应为工作目录。

顺便说下:

ServletActionContext.getServletContext().getRealPath(""))指的是服务器根目录:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\Exercise

ServletActionContext.getServletContext().getRealPath("upload"))->E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\Exercise\upload

不是工作目录。

所以需要配置文件存放 工作目录路径和存放图片目录名

test.properties:

#项目所在路径
workspace=E:/workspace/Exercise
#文件上传目录名
directory=upload
这样在action文件中读取相应的目录

UserAction.java:

private LoadProperties lp = new LoadProperties();//定义properties工具类
public String uploadFile(){
flag = ERROR;
User u  = (User) ServletActionContext.getContext().getSession().get("Login_user");
String targetDirectory = lp.getValue("workspace")+"/WebContent/"+lp.getValue("directory");//读取配置文件中值,组成路径E:/workspace/Exercise/WebConent/upload
uploadFileFileName = user.getId()+"_"+uploadFileFileName;
//生成上传的文件对象
File target = new File(targetDirectory,uploadFileFileName);
//如果文件已经存在,则删除原有文件
if(target.exists()){
target.delete();
}
//复制file对象,实现上传
try {
FileUtils.copyFile(uploadFile, target);
} catch (IOException e) {
e.printStackTrace();
}
String path = lp.getValue("directory")+"/"+uploadFileFileName;//读取配置文件中的值,组成图片路径upload/*.jpg...
user = userService.getUserById(u.getId());
user.setPath(path);
userService.modifyUser(user);
return flag;
}
LoadProperties.java:

private static Properties p = new Properties();

/**
* 读取properties配置文件信息
*/
static{
try {
p.load(LoadProperties.class.getClassLoader().getResourceAsStream("test.properties"));  //src下的test.properties文件
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据key得到value的值
*/
public static String getValue(String key)
{
return p.getProperty(key);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐