zoukankan      html  css  js  c++  java
  • Springmvc框架文件上传单文件上传

    需求:在添加用户信息的时候,非必须上传个人免冠照。

    编写文件上传的时候,要提交的表单必须是method="POST"  enctype="multipart/form-data";

    这是文件上传的思路:

     

       

    下面是文件上传的代码:

    UserDaoImpl.java

     

    UserServiceImpl.java

    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

    // 其中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文件

    <?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

    <%@ 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

     

     运行结果:

     

     运行日志:

    - (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
    

      

     

  • 相关阅读:
    python笔记---@classmethod @staticmethod
    python笔记--socket编程
    python笔记--异常处理
    WebStorm 配置
    ECS node 环境搭建
    spm + host
    Untuntu的apt 终端命令
    Ubuntu 添加至启动栏
    Ubuntu设置镜像源
    Ubuntu 设置中文语言环境
  • 原文地址:https://www.cnblogs.com/dongyaotou/p/12238617.html
Copyright © 2011-2022 走看看