Springmvc框架-文件上传-单文件上传
需求:在添加用户信息的时候,非必须上传个人免冠照。
编写文件上传的时候,要提交的表单必须是method="POST" enctype="multipart/form-data";
这是文件上传的思路:
下面是文件上传的代码:
UserDaoImpl.java
UserServiceImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | package cn.smbms.service.user; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import cn.smbms.dao.BaseDao; import cn.smbms.dao.user.UserDao; import cn.smbms.pojo.User; /** * service层捕获异常,进行事务处理 * 事务处理:调用不同dao的多个方法,必须使用同一个connection(connection作为参数传递) * 事务完成之后,需要在service层进行connection的关闭,在dao层关闭(PreparedStatement和ResultSet对象) * @author Administrator * */ @Service public class UserServiceImpl implements UserService{ @Resource private UserDao userDao; @Override public boolean add(User user) { // TODO Auto-generated method stub boolean flag = false ; Connection connection = null ; try { connection = BaseDao.getConnection(); connection.setAutoCommit( false ); //开启JDBC事务管理 int updateRows = userDao.add(connection,user); connection.commit(); if (updateRows > 0 ){ flag = true ; System.out.println( "add success!" ); } else { System.out.println( "add failed!" ); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); try { System.out.println( "rollback==================" ); connection.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } finally { //在service层进行connection连接的关闭 BaseDao.closeResource(connection, null , null ); } return flag; } @Override public User login(String userCode, String userPassword) { // TODO Auto-generated method stub Connection connection = null ; User user = null ; try { connection = BaseDao.getConnection(); user = userDao.getLoginUser(connection, userCode); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { BaseDao.closeResource(connection, null , null ); } //匹配密码 if ( null != user){ if (!user.getUserPassword().equals(userPassword)) user = null ; } return user; } @Override public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) { // TODO Auto-generated method stub Connection connection = null ; List<User> userList = null ; System.out.println( "queryUserName ---- > " + queryUserName); System.out.println( "queryUserRole ---- > " + queryUserRole); System.out.println( "currentPageNo ---- > " + currentPageNo); System.out.println( "pageSize ---- > " + pageSize); try { connection = BaseDao.getConnection(); userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { BaseDao.closeResource(connection, null , null ); } return userList; } @Override public User selectUserCodeExist(String userCode) { // TODO Auto-generated method stub Connection connection = null ; User user = null ; try { connection = BaseDao.getConnection(); user = userDao.getLoginUser(connection, userCode); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { BaseDao.closeResource(connection, null , null ); } return user; } @Override public boolean deleteUserById(Integer delId) { // TODO Auto-generated method stub Connection connection = null ; boolean flag = false ; try { connection = BaseDao.getConnection(); if (userDao.deleteUserById(connection,delId) > 0 ) flag = true ; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { BaseDao.closeResource(connection, null , null ); } return flag; } @Override public User getUserById(String id) { // TODO Auto-generated method stub User user = null ; Connection connection = null ; try { connection = BaseDao.getConnection(); user = userDao.getUserById(connection,id); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); user = null ; } finally { BaseDao.closeResource(connection, null , null ); } return user; } @Override public boolean modify(User user) { // TODO Auto-generated method stub Connection connection = null ; boolean flag = false ; try { connection = BaseDao.getConnection(); if (userDao.modify(connection,user) > 0 ) flag = true ; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { BaseDao.closeResource(connection, null , null ); } return flag; } @Override public boolean updatePwd( int id, String pwd) { // TODO Auto-generated method stub boolean flag = false ; Connection connection = null ; try { connection = BaseDao.getConnection(); if (userDao.updatePwd(connection,id,pwd) > 0 ) flag = true ; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { BaseDao.closeResource(connection, null , null ); } return flag; } @Override public int getUserCount(String queryUserName, int queryUserRole) { // TODO Auto-generated method stub Connection connection = null ; int count = 0 ; System.out.println( "queryUserName ---- > " + queryUserName); System.out.println( "queryUserRole ---- > " + queryUserRole); try { connection = BaseDao.getConnection(); count = userDao.getUserCount(connection, queryUserName,queryUserRole); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { BaseDao.closeResource(connection, null , null ); } return count; } } |
UserController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | // 其中request对象主要用来存放错误信息,便于前台获取进行相应的提示 @RequestMapping(value = "/useraddsave.html", method = RequestMethod.POST) public String addUserSave( User user, HttpSession session, HttpServletRequest request, @RequestParam(value = "a_idPicPath", required = false) MultipartFile attach) { // 编写文件上传的代码 // 1.判断上传的文件是否为空 String idPicPath = null; // 如果上传的文件不为空 与系统有关的默认名称分隔符。此字段被初始化为包含系统属性 file.separator 的值的第一个字符。在 // UNIX 系统上,此字段的值为 '/';在 Microsoft Windows 系统上,它为 '\\'。 if (!attach.isEmpty()) { String path = request.getSession().getServletContext() .getRealPath("statics" + File.separator + "uploadfiles"); logger.info("uploadFile path ============== > " + path); String oldFileName = attach.getOriginalFilename();// 原来你存在电脑盘符的文件名 logger.info("原来的文件名 ============== > " + oldFileName); String prefix = FilenameUtils.getExtension(oldFileName); logger.info("上传文件的后缀:" + prefix); int filesize = 500000;// 表示文件大小是500k if (attach.getSize() > filesize) { request.setAttribute("uploadFileError", "上传的文件大小不得超过500k"); return "useradd"; // 判断文件的上传文件的格式 } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("pneg")) { String fileName = System.currentTimeMillis() + RandomUtils.nextInt(10000000) + "Personal.jpg"; logger.debug("new fileName======== " + attach.getName()); File targetFile = new File(path, fileName); logger.info("上传到服务器的文件名是:" + targetFile.toString()); // 如果服务器的文件路径存在的话,就进行创建 if (!targetFile.exists()) { /* * mkdirs()可以建立多级文件夹, mkdir()只会建立一级的文件夹, 如下: * new File("/tmp/one/two/three").mkdirs(); * 执行后, 会建立tmp/one/two/three四级目录 * new File("/tmp/one/two/three").mkdir(); * 则不会建立任何目录, 因为找不到/tmp/one/two目录, 结果返回false */ targetFile.mkdirs(); } try { attach.transferTo(targetFile); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); request.setAttribute("uploadFileError", "上传文件失败"); return "useradd"; } idPicPath = path + File.separator + fileName; } } else { request.setAttribute("uploadFileError", " * 上传图片格式不正确"); return "useradd"; } user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)) .getId()); user.setCreationDate(new Date()); user.setIdPicPath(idPicPath); if (userService.add(user)) { return "redirect:/user/userlist.html"; } return "useradd"; } |
修改Spring-servlet.xml文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <? xml version="1.0" encoding="UTF-8"?> < beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> < context:component-scan base-package="cn.smbms.controller"/> < mvc:annotation-driven /> < mvc:resources mapping="/statics/**" location="/statics/" /> <!-- 完成视图的对应 --> <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 --> < bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" > < property name="prefix" value="/WEB-INF/jsp/"/> < property name="suffix" value=".jsp"/> </ bean > <!-- 全局异常处理 --> < bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> < property name="exceptionMappings"> < props > < prop key="java.lang.RuntimeException">error</ prop > </ props > </ property > </ bean > <!--配置MultipartResolver,用于文件上传 --> < bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> < property name="maxUploadSize" value="5000000"></ property > < property name="defaultEncoding" value="UTF-8"></ property > </ bean > </ beans > |
useradd.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/WEB-INF/jsp/common/head.jsp"%> < div class="right"> < div class="location"> < strong >你现在所在的位置是:</ strong > < span >用户管理页面 >> 用户添加页面</ span > </ div > < div class="providerAdd"> < form id="userForm" name="userForm" method="post" action="${pageContext.request.contextPath }/user/useraddsave.html" enctype="multipart/form-data"> < input type="hidden" name="method" value="add"> <!--div的class 为error是验证错误,ok是验证成功--> < div > < label for="userCode">用户编码:</ label > < input type="text" name="userCode" id="userCode" value=""> <!-- 放置提示信息 --> < font color="red"></ font > </ div > < div > < label for="userName">用户名称:</ label > < input type="text" name="userName" id="userName" value=""> < font color="red"></ font > </ div > < div > < label for="userPassword">用户密码:</ label > < input type="password" name="userPassword" id="userPassword" value=""> < font color="red"></ font > </ div > < div > < label for="ruserPassword">确认密码:</ label > < input type="password" name="ruserPassword" id="ruserPassword" value=""> < font color="red"></ font > </ div > < div > < label >用户性别:</ label > < select name="gender" id="gender"> < option value="1" selected="selected">男</ option > < option value="2">女</ option > </ select > </ div > < div > < label for="birthday">出生日期:</ label > < input type="text" Class="Wdate" id="birthday" name="birthday" readonly="readonly" onclick="WdatePicker();"> < font color="red"></ font > </ div > < div > < label for="phone">用户电话:</ label > < input type="text" name="phone" id="phone" value=""> < font color="red"></ font > </ div > < div > < input type="hidden" id="errorinfo" value="${uploadFileError }"/> < label for="a_idPicPath">证件照:</ label > < input type="file" name="a_idPicPath" id="a_idPicPath"> < font color="red"></ font > </ div > < div > < label for="address">用户地址:</ label > < input name="address" id="address" value=""> </ div > < div > < label >用户角色:</ label > <!-- 列出所有的角色分类 --> <!-- <select name="userRole" id="userRole"></select> --> < select name="userRole" id="userRole"> < option value="1">系统管理员</ option > < option value="2">经理</ option > < option value="3" selected="selected">普通用户</ option > </ select > < font color="red"></ font > </ div > < div class="providerAddBtn"> < input type="button" name="add" id="add" value="保存" > < input type="button" id="back" name="back" value="返回" > </ div > </ form > </ div > </ div > </ section > <%@include file="/WEB-INF/jsp/common/foot.jsp" %> < script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/useradd.js"></ script > |
useradd.js
运行结果:
运行日志:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | - ( 72410 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](DispatcherServlet.java: 819 ) DispatcherServlet with name 'springmvc' processing POST request for [/SMBMS_C11_01/user/useraddsave.html] - ( 72931 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](CommonsFileUploadSupport.java: 259 ) Found multipart file [a_idPicPath] of size 33326 bytes with original filename [sunFlower.jpg], stored at [D:\SoftWare\tomcat\apache-tomcat- 6.0 . 53 \work\Catalina\localhost\SMBMS_C11_01\upload__20c85c57_16ff16b9d67__8000_00000008.tmp] - ( 72934 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractHandlerMethodMapping.java: 229 ) Looking up handler method for path /user/useraddsave.html - ( 72935 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractHandlerMethodMapping.java: 234 ) Returning handler method [ public java.lang.String cn.smbms.controller.UserController.addUserSave(cn.smbms.pojo.User,javax.servlet.http.HttpSession,javax.servlet.http.HttpServletRequest,org.springframework.web.multipart.MultipartFile)] - ( 72935 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractBeanFactory.java: 243 ) Returning cached instance of singleton bean 'userController' - ( 72956 ms) - 2020 - 1 - 29 21 : 09 : 19 [ INFO](UserController.java: 193 ) uploadFile path ============== > D:\SoftWare\tomcat\apache-tomcat- 6.0 . 53 \webapps\SMBMS_C11_01\statics\uploadfiles - ( 72956 ms) - 2020 - 1 - 29 21 : 09 : 19 [ INFO](UserController.java: 195 ) 原来的文件名 ============== > sunFlower.jpg - ( 72958 ms) - 2020 - 1 - 29 21 : 09 : 19 [ INFO](UserController.java: 197 ) 上传文件的后缀:jpg - ( 72961 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](UserController.java: 208 ) new fileName======== a_idPicPath - ( 72961 ms) - 2020 - 1 - 29 21 : 09 : 19 [ INFO](UserController.java: 210 ) 上传到服务器的文件名是:D:\SoftWare\tomcat\apache-tomcat- 6.0 . 53 \webapps\SMBMS_C11_01\statics\uploadfiles\1580307319502Personal.jpg - ( 72968 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](CommonsMultipartFile.java: 139 ) Multipart file 'a_idPicPath' with original filename [sunFlower.jpg], stored at [D:\SoftWare\tomcat\apache-tomcat- 6.0 . 53 \work\Catalina\localhost\SMBMS_C11_01\upload__20c85c57_16ff16b9d67__8000_00000008.tmp]: moved to [D:\SoftWare\tomcat\apache-tomcat- 6.0 . 53 \webapps\SMBMS_C11_01\statics\uploadfiles\1580307319502Personal.jpg] add success! - ( 72995 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractAutowireCapableBeanFactory.java: 1557 ) Invoking afterPropertiesSet() on bean with name 'redirect:/user/userlist.html' - ( 72995 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](DispatcherServlet.java: 1198 ) Rendering view [org.springframework.web.servlet.view.RedirectView: name 'redirect:/user/userlist.html' ; URL [/user/userlist.html]] in DispatcherServlet with name 'springmvc' - ( 72995 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](CommonsFileUploadSupport.java: 282 ) Cleaning up multipart file [a_idPicPath] with original filename [sunFlower.jpg], stored at [D:\SoftWare\tomcat\apache-tomcat- 6.0 . 53 \work\Catalina\localhost\SMBMS_C11_01\upload__20c85c57_16ff16b9d67__8000_00000008.tmp] - ( 72995 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](FrameworkServlet.java: 983 ) Successfully completed request - ( 73000 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](DispatcherServlet.java: 819 ) DispatcherServlet with name 'springmvc' processing GET request for [/SMBMS_C11_01/user/userlist.html] - ( 73000 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractHandlerMethodMapping.java: 229 ) Looking up handler method for path /user/userlist.html - ( 73000 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractHandlerMethodMapping.java: 234 ) Returning handler method [ public java.lang.String cn.smbms.controller.UserController.getUserList(org.springframework.ui.Model,java.lang.String,java.lang.String,java.lang.String)] - ( 73000 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractBeanFactory.java: 243 ) Returning cached instance of singleton bean 'userController' - ( 73000 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](DispatcherServlet.java: 906 ) Last-Modified value for [/SMBMS_C11_01/user/userlist.html] is: - 1 - ( 73001 ms) - 2020 - 1 - 29 21 : 09 : 19 [ INFO](UserController.java: 109 ) getUserList ---- > queryUserName: null - ( 73001 ms) - 2020 - 1 - 29 21 : 09 : 19 [ INFO](UserController.java: 110 ) getUserList ---- > queryUserRole: null - ( 73001 ms) - 2020 - 1 - 29 21 : 09 : 19 [ INFO](UserController.java: 111 ) getUserList ---- > pageIndex: null queryUserName ---- > queryUserRole ---- > 0 sql ----> select count( 1 ) as count from smbms_user u,smbms_role r where u.userRole = r.id queryUserName ---- > queryUserRole ---- > 0 currentPageNo ---- > 1 pageSize ---- > 5 sql ----> select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id order by creationDate DESC limit ?,? - ( 73023 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](DispatcherServlet.java: 1198 ) Rendering view [org.springframework.web.servlet.view.JstlView: name 'userlist' ; URL [/WEB-INF/jsp/userlist.jsp]] in DispatcherServlet with name 'springmvc' - ( 73023 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractView.java: 375 ) Added model object 'userList' of type [java.util.ArrayList] to request in view with name 'userlist' - ( 73023 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractView.java: 375 ) Added model object 'roleList' of type [java.util.ArrayList] to request in view with name 'userlist' - ( 73023 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractView.java: 375 ) Added model object 'queryUserName' of type [java.lang.String] to request in view with name 'userlist' - ( 73024 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractView.java: 382 ) Removed model object 'queryUserRole' from request in view with name 'userlist' - ( 73024 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractView.java: 375 ) Added model object 'totalPageCount' of type [java.lang.Integer] to request in view with name 'userlist' - ( 73024 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractView.java: 375 ) Added model object 'totalCount' of type [java.lang.Integer] to request in view with name 'userlist' - ( 73024 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](AbstractView.java: 375 ) Added model object 'currentPageNo' of type [java.lang.Integer] to request in view with name 'userlist' - ( 73024 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](InternalResourceView.java: 236 ) Forwarding to resource [/WEB-INF/jsp/userlist.jsp] in InternalResourceView 'userlist' - ( 73030 ms) - 2020 - 1 - 29 21 : 09 : 19 [DEBUG](FrameworkServlet.java: 983 ) Successfully completed request |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY