• SSM整合+WebUpload使用(spring+springmvc+mybatis+maven)


     

    SSM框架整合以及webupload的集成与使用

    在项目中最近用到了webupload.js,也方方面面遇到了不少问题,比如上传文件前对表单参数校验,当校验失败不予提交,及在文件上传成功后,选择同名文件,则不会显示文件,但可以提交表单。外加一直没有对SSM框架整合没有整理过,借此机会做以学习笔记。遇到的具体问题会在代码注释中说明,以备不时之需,若有不恰之处,还望各位予以指教。

    1、项目结构:

    2、pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.test.ssm</groupId>
      <artifactId>SSM</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>
    
      <name>SSM Maven Webapp</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>
    
      <properties>
        <!-- spring版本号 -->
        <spring.version>4.2.6.RELEASE</spring.version>
        <!-- mybatis版本号 -->
        <mybatis.version>3.4.0</mybatis.version>
        <!-- log4j日志文件管理包版本 -->
        <slf4j.version>1.7.7</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
        <!--jackson版本号-->
        <jackson.version>2.7.1</jackson.version>
    
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>
    
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
          <!--<scope>test</scope>-->
        </dependency>
    
        <!-- spring核心包 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-oxm</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
        </dependency>
    
        <!-- mybatis核心包 -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
        </dependency>
    
        <!-- mybatis/spring包 -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.0</version>
        </dependency>
    
        <dependency>
          <groupId>javax.mail</groupId>
          <artifactId>mail</artifactId>
          <version>1.4</version>
        </dependency>
    
        <!-- 导入Mysql数据库链接jar包 -->
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.30</version>
        </dependency>
        <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
        <dependency>
          <groupId>commons-dbcp</groupId>
          <artifactId>commons-dbcp</artifactId>
          <version>1.2.2</version>
        </dependency>
    
        <!-- JSTL标签类 -->
        <dependency>
          <groupId>jstl</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
        </dependency>
    
        <!-- 日志文件管理包 -->
        <!-- log start -->
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>${log4j.version}</version>
        </dependency>
    
        <!-- 格式化对象,方便输出日志 -->
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.1.41</version>
        </dependency>
    
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>${slf4j.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->
    
        <!-- 映入JSON -->
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>${jackson.version}</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>${jackson.version}</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>${jackson.version}</version>
        </dependency>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
        </dependency>
        <dependency>
          <groupId>javax.servlet.jsp.jstl</groupId>
          <artifactId>javax.servlet.jsp.jstl-api</artifactId>
          <version>1.2.1</version>
        </dependency>
    
        <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-lang3</artifactId>
          <version>3.6</version>
        </dependency>
        
        <!-- commons-fileupload 1.1以后移除了commons-io需要单独引入 -->
        <dependency>
             <groupId>commons-fileupload</groupId>
             <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
         </dependency>
         <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    	<dependency>
    	    <groupId>commons-io</groupId>
    	    <artifactId>commons-io</artifactId>
    	    <version>2.4</version>
    	</dependency>
         
      </dependencies>
    
      <build>
        <finalName>SSM</finalName>
      </build>
    </project>
    

     3、spring-mvc.xml  springmvc配置文件

    <?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:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
        <!-- 自动扫描该包,使用SpringMVC认为包下用了@Controller注解的类是控制器,避免扫描@Service导致事务不能使用 -->
        <context:component-scan base-package = "com.ssm.test">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
        </context:component-scan>
    
       
    	
    	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
    	    <!-- set the max upload size100MB --> 
    	   <property name="maxUploadSize"> 
    	   <value>10485760000</value> 
    	   </property> 
    	   <property name="maxInMemorySize"> 
    	   <value>4096</value> 
    	   </property> 
    	</bean>
    
        <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- 自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
            <property name="prefix" value="/WEB-INF/page/" />
            <property name="suffix" value=".jsp" />
        </bean>
    
        <!-- 添加后可以显示welcome-file界面 -->
        <mvc:default-servlet-handler/>
    
        <!-- 启动注解 -->
        <mvc:annotation-driven />
        
        
    </beans>
    

      4、spring-mybatis.xml 整合spring与mybatis

    <?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:context="http://www.springframework.org/schema/context"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx.xsd">
        <!-- 自动扫描 -->
        <context:component-scan base-package="com.ssm.test">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!-- 引入数据库配置文件 -->
        <bean id = "propertyConfigurer"
              class = "org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
            <property name = "location" value="classpath:jdbc.properties" />
        </bean>
        <!-- 连接池 -->
        <bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource"
              destroy-method = "close">
            <property name="driverClassName" value="${jdbc.driver}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <!-- 初始化连接大小 -->
            <property name="initialSize" value="${jdbc.initialSize}" />
            <!-- 连接池最大数量 -->
            <property name="maxActive" value="${jdbc.maxActive}"/>
            <!-- 连接池最大空闲 -->
            <property name="maxIdle" value="${jdbc.maxIdle}" />
            <!-- 连接池最小空闲 -->
            <property name="minIdle" value="${jdbc.minIdle}" />
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="${jdbc.maxWait}" />
        </bean>
    
        <!-- 结合Spring和Mybatis -->
        <bean id = "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!--给映射的类配置别名,驼峰命名,默认首字母小写-->
            <property name="typeAliasesPackage" value="com.ssm.test.entity"/>
            <!-- 自动扫描mapping.xml文件 -->
            <property name = "mapperLocations" value="classpath:com/ssm/test/mapper/*.xml" />
        </bean>
    
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
        <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name = "basePackage" value="com.ssm.test.dao" />
            <property name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" />
        </bean>
    
        <!-- 定义事务 -->
        <bean id = "transactionManager"
              class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name = "dataSource" ref = "dataSource" />
        </bean>
    
        <!-- 使用注解定义事务 -->
        <tx:annotation-driven transaction-manager = "transactionManager" />
    </beans>
    

      5、jdbc.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/test
    jdbc.username=root
    jdbc.password=123123
    #初始化连接数
    jdbc.initialSize=0
    #最大活跃连接数
    jdbc.maxActive=20
    #最大连接数
    jdbc.maxIdle=20
    #最小连接数
    jdbc.minIdle=1
    #最大等待时间
    jdbc.maxWait=60000
    

      6、log4j.properties配置

    log4j.rootLogger=INFO,Console,File
    log4j.appender.Console=org.apache.log4j.ConsoleAppender
    log4j.appender.Console.Target=System.out
    log4j.appender.Console.layout = org.apache.log4j.PatternLayout
    log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
    
    log4j.appender.File = org.apache.log4j.RollingFileAppender
    log4j.appender.File.File = logs/ssm.log
    log4j.appender.File.MaxFileSize = 10MB
    log4j.appender.File.Threshold = ALL
    log4j.appender.File.layout = org.apache.log4j.PatternLayout
    log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n
    

      7、web.xml配置

    <?xml version="1.0" encoding="UTF-8"?>
    
    <web-app  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://java.sun.com/xml/ns/javaee"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
              version="3.0">
      <display-name>Archetype Created Web Application</display-name>
      <!-- Spring和Mybatis的配置文件 -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mybatis.xml</param-value>
      </context-param>
      <context-param>
        <param-name/>
        <param-value/>
      </context-param>
    
      <!-- 编码过滤器 -->
      <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    
      <!-- Spring监听器 -->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <!-- 防止Spring内存溢出监听器 -->
      <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
      </listener>
    
      <!-- Spring MVC servlet -->
      <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!-- 容器在启动时就加载这个servlet -->
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
      </servlet>
      
    
      <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.do</url-pattern>
      </servlet-mapping>
      
    
      <!-- 设置默认首页 -->
      <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
      </welcome-file-list>
    
    </web-app>
    

      8、创建实体:User.java

    package com.ssm.test.entity;
    
    import java.io.Serializable;
    
    public class User implements Serializable {
    
        private  int id;
        private String name;
        private String password;
        private int age;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
    }
    

      9、创建service接口及实现类

      9.1、UserService.java

    package com.ssm.test.service;
    
    import com.ssm.test.entity.User;
    
    public interface UserService {
        User queryUserInfoById(String id);
    }
    

      9.2、UserServiceImpl.java

    package com.ssm.test.service.impl;
    
    import com.ssm.test.dao.UserDao;
    import com.ssm.test.entity.User;
    import com.ssm.test.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserDao userDao;
    
        @Override
        public User queryUserInfoById(String id) {
            return userDao.queryUserInfoById(id);
        }
    }
    

     10、创建数据交互层接口及对应的mapper文件: 

     10.1、 UserDao.java 

    package com.ssm.test.dao;
    
    import com.ssm.test.entity.User;
    
    public interface UserDao {
    
        User queryUserInfoById(String id);
    }
    

      10.2、User.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.ssm.test.dao.UserDao">
        <select id="queryUserInfoById" parameterType="string" resultType="user">
            select name as name,age as age,password as password from user where id = #{id}
        </select>
    </mapper>
    

    11、创建控制层:UserController.java

    package com.ssm.test.controller;
    
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.ssm.test.entity.User;
    import com.ssm.test.service.UserService;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        private static Logger logger = Logger.getLogger(UserController.class);
        private static final String excelPath = "E:\";
    
        @Autowired
        private UserService userService;
    
        @RequestMapping("/index")
        public ModelAndView index(HttpServletRequest request, ModelAndView model){
            User user = null;
            try {
                String id = request.getParameter("id");
                if (StringUtils.isNotEmpty(id)){
                    user = userService.queryUserInfoById(id);
                }
            model.addObject("name",user.getName());
            model.addObject("age",user.getAge());
            model.addObject("pw",user.getPassword());
            model.setViewName("index");
            } catch (Exception e) {
                logger.error("user异常:",e);
            }
            return model;
        }
        
        @RequestMapping("/upload")
        @ResponseBody
        public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        	
        	String uname = request.getParameter("uname");
        	String pw = request.getParameter("pw");
        	String age = request.getParameter("age");
        	String originalFilename = file.getOriginalFilename();
        	
        	String fileName = excelPath + File.separator + "test"+ File.separator +  originalFilename;
        	
        	File desFile = new File(fileName);
        	if (!desFile.exists()) {
    			desFile.getParentFile().mkdirs();
    		}
        	logger.info("【"+uname+ ","+ age+"岁,密码:"+pw+"】" + "上传文件:"+originalFilename);
        	boolean createFileFlag = createFile(file,desFile);
        	if (createFileFlag) {
        		return "{"state":"succ","msg":"succ"}";
    		}else {
    			return "{"state":"fail","msg":"fail"}";
    		}
        	
        }
    
        private boolean createFile(MultipartFile file,File desFile) {
            boolean flag = false;
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desFile));
                bos.write(file.getBytes());
                bos.flush();
                bos.close();
                flag = true;
            } catch (Exception e) {
                logger.error("【文件上传异常】:",e);
            }
            return flag;
        }
    }
    

      12、创建jsp页面:index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!--获取URL根路径-->
    <%
    	String path = request.getContextPath();
    	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
    			+ path + "/";
    %>
    <html>
    <head>
    	<link rel="stylesheet" href="${basePath}/SSM/css/webuploader.css"/>
    </head>
    <body>
    <form id="uploadForm" enctype="multipart/form-data">
    	<table>
    		<tr>
    			<td>
    				姓名:<input id="uname" value="${name}" type="text">
    			</td>
    		</tr>
    		<tr>
    			<td>
    				年龄:<input id="age" value="${age}" type="text">
    			</td>
    		</tr>
    		<tr>
    			<td>
    				密码:<input id="pw" value="${pw}" type="password">
    			</td>
    		</tr>
    		<tr>
    			<td id="fileList" style=""></td>
    		</tr>
    		<tr>
    			<td id="csvPicker" class="webuploader-container clearfix" style="float: left;"></td>
    			<td id="UploadBtn" class="webuploader-pick clearfix" >开始上传</td>
    		</tr>
    	</table>
    </form>
    <script type="text/javascript" src="${basePath}/SSM/js/jquery/jquery.js"></script>
    <script type="text/javascript" src="${basePath}/SSM/js/webupload/webuploader.js"></script>
    <script type="text/javascript">
    	var $list = $('#fileList');
    	var uploader = WebUploader.create({
    	    // 存在文件自动上传
    	    auto: false,
    	    // swf文件路径
    	    swf: './Uploader.swf',
    	    // 文件接收服务端地址。
    	    server: 'upload.do',
    	    // 选择文件的按钮。
    	    pick: {id: '#csvPicker', label: 'innerHTML', innerHTML: '上传文件', multiple: false},
    	    // 限制文件类型
    	    accept: {title: 'xls,xlsx', extensions: 'xls,xlsx', mimeTypes: 'xls/*,xlsx/*'},
    	    // 是否分片上传
    	    chunked: false,
    	    // 设置分片大小
    	    chunkSize: 5242880,
    	    // 最高并发线程 1
    	    threads: 1,
    	    //允许重复上传
    	    duplicate: true,
    	    // 压缩文件
    	    resize: false,
    	    /** 上传方式 */
    	    method: 'post',
    	    //设定单个文件大小 不能超过20M
    	    fileSingleSizeLimit: 20 * 1024 * 1024,
    	    fileNumLimit:1
    	})
    	// 当有文件被添加进队列的时候
    	uploader.on('fileQueued', function (file) {
    	    $list.append('<div id="' + file.id + '" class="item">' +
    	        '<h4 class="info" style="font-size: 14px;margin-top: 4px;margin-bottom: 5px;">' + file.name + '<button type="button" fileId="' + file.id + '"' +
    	        ' class="btn btn-danger btn-delete" style="padding: 0px 4px;margin-left: 6px;font-size: 5px;background-color: #999999;border-color: #999999;">' +
    	        '<span class="glyphicon glyphicon-trash">X</span></button>' +
    	        '<span class="state" style="display: inline-block; margin-left: 12px">等待上传...</span></h4>' +
    	        '</div>');
    	    /** 删除队列文件 */
    	    $(document).on('click', '.btn-delete', function () {
    	        uploader.removeFile(file,true);
    	        $(this).parent().parent().fadeOut();
    	        $(this).parent().parent().remove();
    	    })
    	});
    	/** 开始上传 */
    	$('#UploadBtn').click(function () {
    	    uploader.upload($('.btn-delete').attr('fileId'))
    	});
    	/** 上传过程中进度条 */
    	uploader.on('uploadProgress', function (file, percentage) {
    	    var $li = $('#' + file.id);
    	    $li.find('.state').text(Math.ceil(percentage * 100) + '%');
    	});
    	/** 完成上传 */
    	uploader.on('uploadSuccess', function (file, reponse) {
    	    if(reponse.state == 'succ'){
    	        alert(reponse.msg);
    	        //this.options.formData.type = '';
    	        this.options.formData.age = '';
    	        this.options.formData.uname = '';
    	        this.options.formData.pw = '';
    	        uploader.removeFile(uploader.getFile(file.id));
    	        uploader.getFiles('inited');
    	    }else{
    	    	//上传失败将文件从队列中移出避免再次添加统一文件时不显示名称
    	        uploader.removeFile(uploader.getFile(file.id));
    	        uploader.getFiles('inited');
    	        alert(reponse.msg);
    	    }
    	});
    	/** 文件上传开始之前 */
    	uploader.on('uploadStart', function (file, reponse) {
    	    var uname = $("#uname").val();
    	    var pw = $("#pw").val();
    	    var age = $("#age").val();
    	   	if(name == null && name == ''){
    	   		alert('姓名不能为空');
    	   		return false;
    	   	}
    	   	if(pw == null && pw == ''){
    	   		alert('密码不能为空');
    	   		return false;
    	   	}
    	    //this.options.formData.type = $("#type option:selected").val();
    	    this.options.formData.uname = uname;
    	    this.options.formData.age = age;
    	    this.options.formData.pw = pw;
    	});
    	/** 上传失败 */
    	uploader.on('uploadError', function (file) {
    	    $('#' + file.id).find('.state').text('上传出错!');
    	});
    	/** 上传完成后执行 */
    	uploader.on('uploadComplete', function (file) {
    	    $('#' + file.id).fadeOut();
    	});
    	/** 文件上传前处理 */
    	uploader.on('beforeFileQueued', function (chunk, data) {
    	    /*
    	    	在文件加入队列之前可以根据需求在此监听事件中加入自己的处理逻辑
    	    */
    	});
    	/**
    	 * 验证文件格式以及文件大小
    	 */
    	uploader.on("error", function (type) {
    	    if (type == "Q_TYPE_DENIED") {
    	        alert("请上传xlsx格式文件");
    	    } else if (type == "F_EXCEED_SIZE") {
    	    	alert("文件大小不能超过20M");
    	    }
    	});
    </script>
    </body>
    </html>
    

      13、测试:

    打开浏览器访问:http://localhost:9090/SSM/user/index.do?id=1

    上传成功后获取到的响应信息提示

    控制台log打印

     

    检查本地文件存储是否存储成功

  • 相关阅读:
    ansible的管理与剧本
    条件随机场入门(二) 条件随机场的模型表示
    条件随机场入门(一) 概率无向图模型
    隐马尔科夫模型
    高斯混合模型 GMM
    K-Means 算法
    EM 算法
    Sequential Minimal Optimization (SMO) 算法
    LinkedIn文本分析平台:主题挖掘的四大技术步骤
    SVM 核方法
  • 原文地址:https://www.cnblogs.com/staticking/p/10096438.html
Copyright © 2020-2023  润新知