servlet3.0 直接提供了上传的组件 使用十分便捷
首先,在要进行上传的servlet文件写上注解
@MultipartConfig
表示这个servlet文件要进行文件上传
前台form表单要修改 enctype="multipart/form-data"
jsp代码:
<form action="user?method=save" onsubmit="return checkForm()" method="post" enctype="multipart/form-data" class="form-horizontal" role="form">
<div class="form-group">
<label for="imagefile" class="col-sm-2 control-label">文件</label>
<div class="col-sm-10" style="padding-top: 5px;">
<input type="file" name = "imagefile" id="imagefile" placeholder="文件">
</div>
</div>
<div class="form-group">
<label for="nickName" class="col-sm-2 control-label">昵称</label>
<div class="col-sm-10">
<input type="text" class="form-control" name = "nickName" id="nickName" value="${currentUser.nickName }" placeholder="昵称">
</div>
</div>
<div class="form-group">
<label for="mood" class="col-sm-2 control-label">心情</label>
<div class="col-sm-10">
<textarea id="mood" name ="mood" class="form-control" rows="10"> ${currentUser.mood } </textarea>
</div>
</div>
<div align="center">
<button type="submit" class="btn btn-primary">保存</button>
<button type="button" class="btn btn-primary" onclick="history.back()" >取消</button>
<font color=red id="error">${error }</font>
</div>
</form>
servlet代码:
@WebServlet("/user")
@MultipartConfig
public class UserServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
if("save".equals(method)){
this.userSave(request, response);
}else{
request.setAttribute("mainPage", "userJSP/userInfo.jsp");
request.getRequestDispatcher("mainTemp.jsp").forward(request, response);
}
}
protected void userSave(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得上传的文件
Part part = request.getPart("imagefile");
System.out.println("submitName:"+part.getSubmittedFileName());
//判断是否上传文件
if(StringUtil.isNotEmpty(part.getSubmittedFileName())){
//获得上传文件的头信息
String contentDesc = part.getHeader("content-disposition");
System.out.println("content-disposition"+ contentDesc);
//上传文件名称包括后缀
String submitName = part.getSubmittedFileName();
System.out.println("submitName:"+submitName);
System.out.println("此文件的大小:"+part.getSize()+"<br />");
System.out.println("此文件类型:"+part.getContentType()+"<br />");
//把文件写到这个路径下
String filePath = PropertiesUtil.getValueForKey("imagePath")+imageName+submitName;
part.write(filePath);
}
}
网友评论