週末閒得無事,就隨便寫寫,如標題所示,玩了一下uploadfy上傳組件,相似uploadfy之類的Flash上傳組件有不少,如SWFUpload、Sapload、AlanXUpload等等,對比以後,我最終選擇了uploadfy。 html
因爲我比較喜歡用SpringMVC,相對於Struts2來講,SpringMVC更輕巧。不扯這些,仍是先來上幾張我一天勞動成果的效果圖吧!
主要作了下使用UploadFy組件實現文件的批量上傳,UploadFy是有帶實時進度信息的,用戶體驗應該還不錯,用戶上傳完成後跳至文件列表頁面,下面的分頁信息是我自定義的分頁標籤,上面就是一些簡單的信息查詢,而後每一個文件均可以點擊「下載」連接直接下載,刪除和編輯功能沒實現,但後臺方法是寫好了的。由於個人重點是學習使用UploadFy組件進行文件上傳下載練習的,因此刪除編輯就忽略了。
這個小示例程序我採用的是SpringMVC + Hibernate4完成的,項目結構圖以下:
依賴的全部jar包如圖:
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"/> java
<!-- 註冊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>
web
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"> spring
<!-- 配置事務管理器 -->
<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> sql
<!-- 配置註解實現管理事務(使用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" /> express
<!-- 配置事務的傳播行爲 -->
<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>
apache
<!-- 配置事務切入點 -->
<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> json
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"> api
<mvc:annotation-driven>
<!-- SpringMVC下載器 -->
<mvc:message-converters>
<bean class="com.yida.framework.base.core.DownloadHttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven> spring-mvc
<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"; } }