首先在jsp页面中,form表单必须要加上enctype=“multipart/form-data”,其次input输入框的而文件类型为file类型。
<form action="${pageContext.request.contextPath}/addUserAction" method="post" enctype="multipart/form-data">
。。。
<div class="form-group row">
<label class="col-sm-3 form-control-label">头像</label>
<div class="col-sm-9">
<input type="file" name="headImg" value="">
</div>
</div>
。。。
</form>
在action中,使用属性驱动获取jsp中上传文件的值
public class UserAction extends ActionSupport implements ModelDriven<User>{
private File headImg;
private String headImgFileName;
@Action("addUserAction")
public String addUserAction() throws IOException {
System.out.println(headImg);
if(user!=null) {
if(headImg!=null) {
String filePath=ServletActionContext.getServletContext().getRealPath("/upload/pic");
String fileName=UUID.randomUUID().toString().replace("-", "")
+headImgFileName.substring(headImgFileName.lastIndexOf("."));
FileUtils.copyFile(headImg, new File(filePath,fileName));
user.setUrl("/upload/pic/"+fileName);
}
}
return "addUser";
}
这样就可以实现图片的上传