struts2上传文件
1.form表单
<form class="form-horizontal" onkeydown="if(event.keyCode==13)return false;" action="/user/updatePro.do" method="post" role="form" id="updateUserForm" enctype="multipart/form-data"> <input type="hidden" name="id" value="${user.id}"> <div class="form-group"> <label for="pic" class="col-sm-2 control-label">头像</label> <div class="col-sm-4"> <input type="file" name="pic2" id="pic" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default" id="updateUserBtn">修改</button> </div> </div> </form>
2.后台处理
package cn.getword.action; import cn.getword.domain.User; import cn.getword.service.UserService; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.util.*; @Controller @ParentPackage("my-default") @Namespace("/user") public class UserAction extends ActionSupport implements ModelDriven<User> { @Autowired private UserService userService; private User user = new User(); private String pic2FileName; // 获取原始文件名,同理可以获取文件File @Action(value = "update", results = {@Result(location = "/WEB-INF/views/updateUser.jsp")}) public String updateUser() { HttpServletRequest request = ServletActionContext.getRequest(); User user1 = userService.getUserById(user.getId()); request.setAttribute("user", user1); return SUCCESS; } @Action(value = "updatePro", results = {@Result(name = "success", type = "redirect", location = "/index.do"), @Result(name = "input", type = "redirect", location = "/index.do") }) public String updateUserPro() { HttpServletRequest request = ServletActionContext.getRequest(); String pic = request.getParameter("pic2"); if (ServletFileUpload.isMultipartContent(request)) { File[] pics = ((MultiPartRequestWrapper) request).getFiles("pic2"); if (pics.length > 0) { File file = pics[0]; String path = "/upload/images/user"; LocalDate now = LocalDate.now(); path += "/" + now.getYear() + now.getMonthValue() + now.getDayOfMonth(); File dir = new File(request.getServletContext().getRealPath(path)); if (!dir.exists()) { dir.mkdirs(); } String filename = file.getName(); String ext = filename.substring(filename.lastIndexOf(".") + 1); //判断是否需要覆盖 User u1 = userService.getUserById(user.getId()); String filepath = u1.getPic(); //虚拟目录 if (user.getPic() == null) { filepath = path + "/" + UUID.randomUUID().toString().replace("-", "") +"."+ ext; user.setPic(filepath); } File uploadFile = new File(request.getServletContext().getRealPath(filepath)); //目标路径 try { FileUtils.copyFile(file, uploadFile); } catch (IOException e) { e.printStackTrace(); } rs = userService.updateUser(user); } return SUCCESS; } return INPUT; } //====================== @Override public User getModel() { return user; } public void setUserService(UserService userService) { this.userService = userService; } public String getPic2FileName() { return pic2FileName; } public void setPic2FileName(String pic2FileName) { this.pic2FileName = pic2FileName; } }
end