在做struts2上传的时候是很简单的,虽然是个入侵式的框架,但是做文件的操作还是很方便的。
如做图片上传的时候,只需要在jsp页面内有type为file的属性即可。
<img src="${basePath}upload/<s:property value='user.headImg'/>" width="100" height="100"/>
<%-- <s:hidden>
<s:param name="user.headImg"><s:property value ="user.headImg"/></s:param>
</s:hidden> --%>
<s:hidden name="user.headImg"/>
<input type="file" name="headImg"/>
然后再action层加上file,fileContentType,fileName即可。使用
FileUtils.copyFile();工具类,很好的实现了图片上传。
action代码如下:
public class UserAction extends ActionSupport {
@Resource
private UserService userService;
private List<User> userList;
private User user;
private String[] selectedRow;
// 设置文件上传
private File headImg;
private String headImgContentType;
private String headImgFileName;
// 列表页面
public String listUI() {
userList = userService.findObjects();
return "listUI";
}
// 跳转到新增页面
public String addUI() {
return "addUI";
}
// 保存新增
public String add() {
if (user != null) {
userService.save(user);
}
return "list";
}
// 跳转到编辑页面
public String editUI() {
if (user != null && user.getId() != null) {
user = userService.findObjectById(user.getId());
}
return "editUI";
}
// 保存编辑
public String edit() {
try {
if (user != null) {
if (headImg != null) {
String filepath = ServletActionContext.getServletContext().getRealPath("upload/user");
String filename = UUID.randomUUID().toString().replace("-", "")+headImgFileName.substring(headImgFileName.lastIndexOf("."));;
FileUtils.copyFile(headImg, new File(filepath,filename));
user.setHeadImg("user/"+filename);
}
userService.update(user);
}
} catch (Exception e) {
e.printStackTrace();
}
return "list";
}
// 删除
public String delete() {
if (user != null && user.getId() != null) {
userService.delete(user.getId());
}
return "list";
}
// 批量删除
public String deleteSelected() {
if (selectedRow != null) {
for (String id : selectedRow) {
userService.delete(id);
}
}
return "list";
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String[] getSelectedRow() {
return selectedRow;
}
public void setSelectedRow(String[] selectedRow) {
this.selectedRow = selectedRow;
}
public File getHeadImg() {
return headImg;
}
public void setHeadImg(File headImg) {
this.headImg = headImg;
}
public String getHeadImgContentType() {
return headImgContentType;
}
public void setHeadImgContentType(String headImgContentType) {
this.headImgContentType = headImgContentType;
}
public String getHeadImgFileName() {
return headImgFileName;
}
public void setHeadImgFileName(String headImgFileName) {
this.headImgFileName = headImgFileName;
}
}