uploadify + SpringMVC文件批量上传及下载

周末闲得无事,就随便写写,如标题所示,玩了一下uploadfy上传组件,类似uploadfy之类的Flash上传组件有很多,如SWFUpload、Sapload、AlanXUpload等等,对比之后,我最终选择了uploadfy。

   由于我比较喜欢用SpringMVC,相对于Struts2来说,SpringMVC更轻巧。不扯这些,还是先来上几张我一天劳动成果的效果图吧!
  uploadify + SpringMVC文件批量上传及下载_第1张图片

uploadify + SpringMVC文件批量上传及下载_第2张图片

uploadify + SpringMVC文件批量上传及下载_第3张图片

uploadify + SpringMVC文件批量上传及下载_第4张图片

uploadify + SpringMVC文件批量上传及下载_第5张图片
主要做了下使用UploadFy组件实现文件的批量上传,UploadFy是有带实时进度信息的,用户体验应该还不错,用户上传完成后跳至文件列表页面,下面的分页信息是我自定义的分页标签,上面就是一些简单的信息查询,然后每个文件都可以点击“下载”链接直接下载,删除和编辑功能没实现,但后台方法是写好了的。因为我的重点是学习使用UploadFy组件进行文件上传下载练习的,所以删除编辑就忽略了。
    这个小示例程序我采用的是SpringMVC + Hibernate4完成的,项目结构图如下:
uploadify + SpringMVC文件批量上传及下载_第6张图片

依赖的所有jar包如图:
uploadify + SpringMVC文件批量上传及下载_第7张图片

applicationContext.xml配置:
<!-- 基于注解自动扫描组件  去掉spring controll,如果不去除会影响事务管理-->
 <context:component-scan base-package="com.yida.framework" annotation-config="true"> 
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
   
    <!-- enable autowire -->
 <context:annotation-config />
   
 <!-- hibernate属性配置文件 多个可以用逗号分割 -->
 <context:property-placeholder location="classpath:/com/yida/framework/base/config/db/jdbc.properties"/>

 
    <!-- 注册SessionFactory 使用JPA注解就不能使用LocalSessionFactoryBean,而对于Hibernate4,AnnotationSessionFactoryBean和LocalSessionFactoryBean统一合并为LocalSessionFactoryBean了 -->
 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" scope="singleton">
        <property name="dataSource">
      <ref bean="dataSource" />
     </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
             <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
             <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
             <prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>
            </props>
        </property>
        <property name="packagesToScan">
          <list>
              <value>com.yida.framework.modules.po</value>
          </list>
          </property>
    </bean>
   
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName">
   <value>${hibernate.jdbc.driverClassName}</value>
  </property>
  <property name="url">
   <value>${hibernate.jdbc.url}</value>
  </property>
  <property name="username">
   <value>${hibernate.jdbc.username}</value>
  </property>
  <property name="password">
   <value>${hibernate.jdbc.password}</value>
  </property>
 </bean>
   
    <!-- 注册Spring的模版对象 -->
 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

applicationContext-transaction.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"
 xmlns:aop="
http://www.springframework.org/schema/aop"
 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/aop   
            
 http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
            
 http://www.springframework.org/schema/tx   
            
 http://www.springframework.org/schema/tx/spring-tx-3.1.xsd  
            
 http://www.springframework.org/schema/mvc   
            
 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd  
            
 http://www.springframework.org/schema/context   
            
 http://www.springframework.org/schema/context/spring-context-3.1.xsd">

 <!-- 配置事务管理器 -->
 <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
  <!-- Hibernate4的TransactionManager需要配置dataSource,而hibernate3只需要配置一个SessionFactory -->
  <property name="dataSource" ref="dataSource"/>
 </bean>

 <!-- 配置注解实现管理事务(使用cglib方式实现AOP时:proxy-target-class="true") -->
 <!-- 
 <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
    -->
   
    <!-- 开启AOP监听 指定使用aspectj方式 -->
 <aop:aspectj-autoproxy proxy-target-class="true" />

 <!-- 配置事务的传播行为 -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="get*" propagation="REQUIRED" read-only="true" />
   <tx:method name="add*" propagation="REQUIRED" />
   <tx:method name="edit*" propagation="REQUIRED" />
   <tx:method name="remove*" propagation="REQUIRED" />
   <tx:method name="save*" propagation="REQUIRED" />
   <tx:method name="update*" propagation="REQUIRED" />
   <tx:method name="delete*" propagation="REQUIRED" />
   <tx:method name="batch*" propagation="REQUIRED" />
   <tx:method name="bulk*" propagation="REQUIRED" />
   <tx:method name="*" read-only="true" />
  </tx:attributes>
 </tx:advice>
 

 <!-- 配置事务切入点 -->
 <aop:config>
  <aop:pointcut id="targetMethod" expression="execution(* com.yida.framework.modules.service.impl.*.*(..))" />
  <aop:advisor advice-ref="txAdvice" pointcut-ref="targetMethod" />
 </aop:config>
</beans>

 

SpringMVC-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"
 xmlns:aop="
http://www.springframework.org/schema/aop"
 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/aop   
            
 http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
            
 http://www.springframework.org/schema/tx   
            
 http://www.springframework.org/schema/tx/spring-tx-3.1.xsd  
            
 http://www.springframework.org/schema/mvc   
            
 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd  
            
 http://www.springframework.org/schema/context   
            
 http://www.springframework.org/schema/context/spring-context-3.1.xsd">

 
 <mvc:annotation-driven>
     <!-- SpringMVC下载器 -->
  <mvc:message-converters> 
         <bean class="com.yida.framework.base.core.DownloadHttpMessageConverter" /> 
     </mvc:message-converters>
 </mvc:annotation-driven> 

 <context:annotation-config />

 <!-- SpringMVC拦截器 -->
 <mvc:interceptors>
  <mvc:interceptor>
   <mvc:mapping path="*.jsp" />
   <ref bean="localeChangeInterceptor"/>
  </mvc:interceptor>
 </mvc:interceptors>

 <!-- SpringMVC @controller组件检测,去除掉@Service注解,注意use-default-filters="false"-->
 <context:component-scan base-package="com.yida.framework.modules.web.controller" use-default-filters="false">
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
 </context:component-scan>

 <!-- SpringMVC3.1 协商视图解析器(即自动根据请求头信息中的contentType选择视图解析器)-->
 <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="ignoreAcceptHeader" value="true" />
  <property name="favorParameter" value="false" />
  <property name="defaultContentType" value="text/html" />
  <property name="mediaTypes">
   <map>
    <entry key="html" value="text/html" />
    <entry key="xml" value="application/xml" />
    <entry key="json" value="application/json" />
   </map>
  </property>
  <property name="viewResolvers">
   <list>
    <ref bean="jspViewResolver" />
    <ref bean="freeMarkerViewResolver" />
   </list>
  </property>
  <property name="defaultViews">
   <list>
    <ref bean="jacksonJsonView" />
    <ref bean="xStreamView" />
   </list>
  </property>
 </bean>

 <!-- jstlView视图 -->
 <!-- 
 <bean id="jstlView" class="org.springframework.web.servlet.view.JstlView"></bean>
 -->

 <!-- jacksonJsonView视图 -->
 <bean name="jacksonJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
  <property name="contentType">
   <value>text/html;charset=UTF-8</value>
  </property>
 </bean>

 <!-- XStreamMarshaller XML视图 -->
 <bean id="xStreamView" class="org.springframework.web.servlet.view.xml.MarshallingView">
  <property name="marshaller">
   <bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
  </property>
 </bean>

 <!-- JSP视图解析器 -->
 <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/jsp/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
  <property name="viewClass">
   <value>org.springframework.web.servlet.view.JstlView</value>
  </property>
  <!-- 优先级 -->
  <property name="order">
   <value>1</value>
  </property>
 </bean>

 <!-- FreeMarker视图解析器 -->
 <bean id="freeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
  <property name="suffix">
   <value>.ftl</value>
  </property>
  <property name="prefix">
   <value>freemarker</value>
  </property>
  <property name="cache">
   <value>true</value>
  </property>
  <property name="order">
   <value>2</value>
  </property>
  <property name="viewClass">
   <value>org.springframework.web.servlet.view.freemarker.FreeMarkerView</value>
  </property>
  <property name="contentType" value="text/html;charset=utf-8" />
  <property name="exposeRequestAttributes" value="true" />
  <property name="exposeSessionAttributes" value="true" />
  <property name="exposeSpringMacroHelpers" value="true" />
  <property name="requestContextAttribute" value="request" />
 </bean>

 <!-- FreeMarker配置 -->
 <bean id="freemarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  <property name="templateLoaderPath">
   <value>/freemarker/</value>
  </property>
  <property name="freemarkerSettings">
   <props>
    <prop key="template_update_delay">10000000</prop>
    <prop key="locale">zh_CN</prop>
    <prop key="defaultEncoding">UTF-8</prop>
    <prop key="url_escaping_charset">UTF-8</prop>
    <prop key="boolean_format">true,false</prop>
    <prop key="datetime_format">yyyy-MM-dd</prop>
    <prop key="date_format">yyyy-MM-dd</prop>
    <prop key="number_format">#.##</prop>
    <prop key="classic_compatible">true</prop>
    <prop key="whitespace_stripping">true</prop>
   </props>
  </property>
 </bean>

 <!-- velocitly视图解析器 -->
 <!--
  <bean id="velocitlyViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property
  name="viewClass"> <value>org.springframework.web.servlet.view.velocity.VelocityView</value> </property> <property name="prefix">
  <value>/velocitly/</value> </property> <property name="suffix"> <value>.vm</value> </property> <property name="contentType">
  <value>text/html;charset=utf-8</value> </property> <property name="exposeRequestAttributes"> <value>true</value> </property>
  <property name="exposeSessionAttributes"> <value>true</value> </property> <property name="exposeSpringMacroHelpers">
  <value>true</value> </property> </bean>
 -->

 <!-- velocity配置 -->
 <!--
  <bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property
  name="resourceLoaderPath"> <value>/velocitly/</value> </property> <property name="velocityProperties"> <props> <prop
  key="file.resource.loader.cache">false</prop> <prop key="directive.foreach.counter.name">loopCounter</prop> <prop
  key="directive.foreach.counter.initial.value">0</prop> <prop key="input.encoding">UTF-8</prop> <prop
  key="output.encoding">UTF-8</prop> </props> </property> </bean>
 -->

 <!-- XSLT View视图 -->
 <!-- 
 <bean id="xsltView" class="org.springframework.web.servlet.view.xslt.XsltView"></bean>
 -->

 <!-- XSLT View视图解析器 -->
 <!--
  <bean id="xsltViewResolver" class="org.springframework.web.servlet.view.xslt.XsltViewResolver"> <property name="viewClass">
  <value>org.springframework.web.servlet.view.xslt.XsltView</value> </property> <property name="sourceKey" value="logins">
  <value>logins</value> </property> <property name="prefix"> <value>/xslt/</value> </property> <property name="suffix">
  <value>.xslt</value> </property> </bean>
 -->

 <!-- Tiles视图 -->
 <!-- 
 <bean id="tilesView" class="org.springframework.web.servlet.view.tiles.TilesView"></bean>
 -->

 <!-- tiles配置器-->
 <!--
  <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles.TilesConfigurer"> <property name="definitions">
  <list> <value>/WEB-INF/train-def.xml</value> </list> </property> </bean>
 -->

 <!-- SpringMVC文件上传 -->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- 解析request的编码 ,Default is ISO-8859-1 -->
  <property name="defaultEncoding">
      <value>UTF-8</value>
  </property>
  <!-- 设置上传文件最大20MB -->
  <property name="maxUploadSize">
   <value>20971520</value>
  </property>
  <property name="maxInMemorySize">
   <value>4096</value>
  </property>
 </bean>

 <!-- 国际化资源配置 -->
 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="message"/>

 <!-- 国际化拦截器 -->
 <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>

 <!-- JSON转换器 -->
 <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
  <property name="supportedMediaTypes">
   <list>
    <value>application/json;charset=UTF-8</value>
    <value>text/html;charset=UTF-8</value>
   </list>
  </property>
 </bean>

 <!-- XML转换器 -->
 <!--
  <bean id="marshallingConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"> <constructor-arg
  ref="jaxbMarshaller" /> <property name="supportedMediaTypes"> <list> <value>application/xml;charset=UTF-8</value>
  <value>text/html;charset=UTF-8</value> </list> </property> </bean> <bean id="jaxbMarshaller"
  class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> <property name="classesToBeBound"> <list>
  <value>springmvc3.bean.Student</value> <value>springmvc3.bean.StudentList</value> </list> </property> </bean>
 -->

 <!-- 异常处理器 -->
 <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
              <props>
                  <prop key="java.lang.Exception">
                        error
                </prop>
            </props>
        </property>
    </bean>

 <!-- 配置静态资源 -->
 <mvc:resources mapping="/images
@Controller
@RequestMapping(value="/file")
public class FileController extends BaseController<IFileService> {
 
 
 @RequestMapping(value="/toUploadFile.do",method=RequestMethod.GET)
 public String toUploadFile(){
  return "upload";
 }
 
 
 @RequestMapping(value="/uploadFile.do",method=RequestMethod.POST)
 public String uploadFile(MultipartHttpServletRequest request,
   @ModelAttribute("fileModel")FileModel fileModel,ModelMap modelMap){
  String realPath = request.getRealPath("/" + Globarle.UPLOAD_DIR);
  File file = new File();
  file.setServerPath(realPath);
  boolean uploadSuccess = getService().addFile(file, request.getFiles("file"));
  String message = uploadSuccess?"上传成功!" : "上传失败!";
  return "list";
 }
 
 
 @RequestMapping(value="/updateFile.do",method=RequestMethod.POST)
 public String updateFile(@ModelAttribute("fileModel")FileModel fileModel,ModelMap modelMap){
  File file = new File();
  MyBeanUtils.copyProperties(file, fileModel);
  int result = getService().updateFile(file);
  String message = (result == -1)? "更新失败!" : "更新成功!";
  modelMap.put("msg", message);
  return "forward:file/toUpdateFile.do";
 }
 
 
 @RequestMapping(value="/toUpdateFile.do",method=RequestMethod.GET)
 public String toUpdateFile(@ModelAttribute("fileModel")FileModel fileModel,ModelMap map){
  File file = getService().findFileById(fileModel.getId());
  map.put("file",file);
  return "edit";
 }
 
 
 @RequestMapping(value="/batchDeleteFile.do",method=RequestMethod.GET)
 public String batchDeleteFile(HttpServletRequest request,
  @ModelAttribute("fileModel")FileModel fileModel,ModelMap modelMap){
  int result = getService().batchDeleteFile(fileModel.getIdArray(), request.getRealPath("/" + Globarle.UPLOAD_DIR));
  String message = (result == -1)? "批量删除失败!" : "批量删除成功!";
  modelMap.put("msg", message);
  return "forward:file/listFile.do";
 }
 
 
 @RequestMapping(value="/downloadFile.do",method=RequestMethod.GET)
 @ResponseBody
 public DownloadHelper downloadFile(HttpServletRequest request, 
  @ModelAttribute("fileModel")FileModel fileModel){
  //boolean isSuccess = false;
  String realPath = request.getRealPath("/" + Globarle.UPLOAD_DIR);
  File file = getService().findFileById(fileModel.getId());
  String fileName = realPath + "\" + file.getFileName();
  DownloadHelper downloadHelper = new DownloadHelper();  
  downloadHelper.setFile(new java.io.File(fileName));  
     //指定下载文件名  
  //downloadHelper.setFileName(file.getFileName());  
  //downloadHelper.setCharset(Charset.forName("UTF-8"));
  return downloadHelper;
 }
 
 
 @RequestMapping(value="/listFile.do")
 public String list(@ModelAttribute("fileModel")FileModel fileModel,ModelMap map){
  PageData pageData = getService().findFilesForPage(fileModel);
  map.put("pageData", pageData);
  return "list";
 }
}

你可能感兴趣的:(uploadify + SpringMVC文件批量上传及下载)