您的位置:首页 > 编程语言 > Java开发

struts2头像上传练习及其注意事项

2016-03-03 20:20 435 查看
1.jsp页面

<form id="form" name="form" action="${basePath}nsfw/user_add.action" method="post" enctype="multipart/form-data">

...

<tr>
<td class="tdBg" width="200px">头像:</td>
<td>
<input type="file" name="headImg"/>
</td>
</tr>


  注意:form表单要加 enctype="multipart/form-data" ,头像的input要使用file类型

2.action控制器

//头像上传
private File headImg;
private String headImgContentType;
private String headImgFileName;

...

//保存新增
public String add(){
try {
if(user != null){
System.out.println(headImg);
//处理头像
if(headImg != null){
//1.保存头像到upload/user
//获取保存路径的绝对地址
String filePath = ServletActionContext.getServletContext().getRealPath("/upload/user");
System.out.println(filePath);
String fileName = UUID.randomUUID().toString().replaceAll("-", "")+headImgFileName.substring(headImgFileName.lastIndexOf("."));
//复制文件
FileUtils.copyFile(headImg, new File(filePath, fileName));

//2、设置用户头像路径
user.setHeadImg("user/" + fileName);
}
userService.save(user);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "list";
}


  注意: private File headImg; 的名字要与jsp页面传来的名字(name)一致

出现过的问题:

String filePath = ServletActionContext.getServletContext().getRealPath("/upload/user");这行代码的 "/upload/user" 写成"upload/user" 时,不会把文件上传到服务器。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: