怎麼把文本域和二進制數據一塊兒提交到Controller裏面? 故本文來探討這個問題,把本身踩到的坑分享出來javascript
hibernate+springmvc+jsphtml
功能實現:form頁面填寫文本字段+文件,點擊提交按鈕一塊兒提交到後臺java
數據庫mysql使用LongBlob字段存儲,對應java的byte[]類型mysql
提示:在真實生產環境中不推薦使用數據庫直接存儲圖片文件!可是本文爲了突出說明技術重點和難點。因此使用了這種簡單的辦法git
PS:這個POM很長,不須要參考的話直接拖下去...github
<?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.hellobike.zhangjianan</groupId> <artifactId>zjngraduationdesign</artifactId> <version>1.1.0</version> <packaging>war</packaging> <name>zjngraduationdesign</name> <url>http://www.zhangjianan.com</url> <!-- 項目屬性 --> <properties> <!-- version setting --> <spring.version>3.2.5.RELEASE</spring.version><!-- <spring-data-jpa.version>1.3.0.RELEASE</spring-data-jpa.version> --> <hibernate.version>4.2.0.Final</hibernate.version> <hibernate-search.version>4.2.0.Final</hibernate-search.version> <hibernate-validator.version>5.0.1.Final</hibernate-validator.version> <mybatis.version>3.2.3</mybatis.version> <mybatis-spring.version>1.2.1</mybatis-spring.version> <druid.version>1.0.1</druid.version> <shiro.version>1.2.2</shiro.version> <ehcache.version>2.6.6</ehcache.version> <sitemesh.version>2.4.2</sitemesh.version> <activiti.version>5.14</activiti.version> <slf4j.version>1.7.5</slf4j.version> <log4j.version>1.2.17</log4j.version> <commons-lang3.version>3.1</commons-lang3.version> <commons-io.version>2.4</commons-io.version> <commons-codec.version>1.8</commons-codec.version> <commons-fileupload.version>1.3</commons-fileupload.version> <commons-beanutils.version>1.8.3</commons-beanutils.version> <jackson.version>2.2.1</jackson.version> <xstream.version>1.4.3</xstream.version> <guava.version>14.0.1</guava.version> <dozer.version>5.4.0</dozer.version> <poi.version>3.9</poi.version> <freemarker.version>2.3.19</freemarker.version> <!-- jdbc driver setting --> <mysql.driver.version>5.1.13</mysql.driver.version> <oracle.driver.version>10.2.0.1.0</oracle.driver.version> <mssql.driver.version>1.2.4</mssql.driver.version> <!-- other setting --> <jdk.version>1.6</jdk.version> <tomcat.version>2.1</tomcat.version> <jetty.version>7.6.10.v20130312</jetty.version> <webserver.port>8181</webserver.port> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <downloadSources>false</downloadSources> </properties> <!-- 設定除中央倉庫(repo1.maven.org/maven2/)外的其餘倉庫,按設定順序進行查找. --> <repositories> <!-- 若有Nexus私服, 取消註釋並指向正確的服務器地址. <repository> <id>nexus-repos</id> <name>Team Nexus Repository</name> <url>http://localhost:8081/nexus/content/groups/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> --> <repository> <id>central-repos</id> <name>Central Repository</name> <url>http://repo.maven.apache.org/maven2</url> </repository> <repository> <id>central-repos2</id> <name>Central Repository 2</name> <url>http://repo1.maven.org/maven2/</url> </repository> <repository> <id>springsource-repos</id> <name>SpringSource Repository</name> <url>http://repo.springsource.org/libs-milestone-local</url> </repository> <repository> <id>activiti-repos</id> <name>Activiti Repository</name> <url>https://maven.alfresco.com/nexus/content/groups/public</url> </repository> <repository> <id>activiti-repos2</id> <name>Activiti Repository 2</name> <url>https://app.camunda.com/nexus/content/groups/public</url> </repository> <repository> <id>thinkgem-repos</id> <name>ThinkGem Repository</name> <url>http://git.oschina.net/thinkgem/repos/raw/master</url> </repository> <repository> <id>thinkgem-repos2</id> <name>ThinkGem Repository 2</name> <url>https://raw.github.com/thinkgem/repository/master</url> </repository> </repositories> <pluginRepositories> <!-- 若有Nexus私服, 取消註釋並指向正確的服務器地址. <pluginRepository> <id>nexus-repos</id> <name>Team Nexus Repository</name> <url>http://localhost:8081/nexus/content/groups/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> --> </pluginRepositories> <!-- 依賴項定義 --> <dependencies> <!-- ERMaster begin --> <dependency> <groupId>org.eclipse</groupId> <artifactId>swt</artifactId> <version>3.3.0-v3346</version> </dependency> <dependency> <groupId>org.eclipse</groupId> <artifactId>draw2d</artifactId> <version>3.2.100-v20070529</version> </dependency> <dependency> <groupId>org.eclipse</groupId> <artifactId>jface</artifactId> <version>3.3.0-I20070606-0010</version> </dependency> <dependency> <groupId>org.insightech.er</groupId> <artifactId>ERMaster</artifactId> <version>20121127-2328</version> <scope>system</scope> <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/org.insightech.er_1.0.0.v20121127-2328.jar</systemPath> </dependency> <!-- ERMaster end --> <dependency> <groupId>bitwalker</groupId> <artifactId>UserAgentUtils</artifactId> <version>1.13</version> </dependency> <dependency> <groupId>org.zeroturnaround</groupId> <artifactId>zt-zip</artifactId> <version>1.6</version> <type>jar</type> </dependency> <!-- SPRING begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</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-aop</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!-- spring orm --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- spring data jpa <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>${spring-data-jpa.version}</version> <exclusions> <exclusion> <groupId>junit</groupId> <artifactId>junit-dep</artifactId> </exclusion> </exclusions> </dependency> --> <!-- SPRING end --> <!-- AOP begin --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> <scope>runtime</scope> </dependency> <!-- AOP end --> <!-- PERSISTENCE begin --> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency><!-- jpa <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate-validator.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-search</artifactId> <version>${hibernate-search.version}</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- 中文分詞 --> <dependency> <groupId>org.wltea</groupId> <artifactId>analyzer</artifactId> <version>2012_u6</version> </dependency> <!-- connection pool --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- jdbc driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>${oracle.driver.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>net.sourceforge.jtds</groupId> <artifactId>jtds</artifactId> <version>${mssql.driver.version}</version> <scope>runtime</scope> </dependency> <!-- PERSISTENCE end --> <!-- WEB begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</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-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>opensymphony</groupId> <artifactId>sitemesh</artifactId> <version>${sitemesh.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <type>jar</type> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <type>jar</type> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <!-- WEB end --> <!-- EHCACHE begin --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>${ehcache.version}</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-web</artifactId> <version>2.0.4</version> </dependency> <!-- EHCACHE end --> <!-- SECURITY begin --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${shiro.version}</version> </dependency> <!-- SECURITY end --> <!-- Activiti --> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-engine</artifactId> <version>${activiti.version}</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring</artifactId> <version>${activiti.version}</version> </dependency> <dependency> <groupId>org.eclipse</groupId> <artifactId>draw2d</artifactId> <version>3.2.100-v20070529</version> </dependency> <!-- LOGGING begin --> <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> <scope>runtime</scope> </dependency> <!-- common-logging 實際調用slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <!-- java.util.logging 實際調用slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- log4jdbc --> <dependency> <groupId>org.lazyluke</groupId> <artifactId>log4jdbc-remix</artifactId> <version>0.2.7</version> <scope>runtime</scope> </dependency> <!-- LOGGING end --> <!-- GENERAL UTILS begin --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>${commons-codec.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>${commons-beanutils.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- google java library --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>${guava.version}</version> </dependency> <!-- jackson 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>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jaxb-annotations</artifactId> <version>${jackson.version}</version> </dependency> <!-- xstream xml --> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>${xstream.version}</version> </dependency> <!-- pojo copy --> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>${dozer.version}</version> </dependency> <!-- freemarker engine --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>${freemarker.version}</version> </dependency> <!-- email --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <!-- poi office --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>${poi.version}</version> </dependency> <!-- image util --> <dependency> <groupId>com.drewnoakes</groupId> <artifactId>metadata-extractor</artifactId> <version>2.6.2</version> </dependency> <!-- GENERAL UTILS end --> <!-- CKFinder begin --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.2</version> </dependency> <dependency> <groupId>com.ckfinder</groupId> <artifactId>apache-ant-zip</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>com.ckfinder</groupId> <artifactId>ckfinder</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>com.ckfinder</groupId> <artifactId>ckfinderplugin-fileeditor</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>com.ckfinder</groupId> <artifactId>ckfinderplugin-imageresize</artifactId> <version>2.3</version> </dependency> <!-- CKFinder end --> <!-- TEST begin --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- TEST end --> <!-- 自定義jar依賴包 <dependency> <groupId>com.test</groupId> <artifactId>test-core</artifactId> <version>1.0</version> <scope>system</scope> <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/test-core-1.0.jar</systemPath> </dependency> --> </dependencies> <build> <outputDirectory>${project.basedir}/src/main/webapp/WEB-INF/classes/</outputDirectory> <plugins> <!-- Compiler 插件, 設定JDK版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> <showWarnings>true</showWarnings> </configuration> </plugin> <!-- war 打包插件, 設定war包名稱不帶版本號 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <warName>${project.artifactId}</warName> </configuration> </plugin> <!-- Eclipse 插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <downloadSources>${downloadSources}</downloadSources> <downloadJavadocs>false</downloadJavadocs> <wtpversion>2.0</wtpversion> <sourceIncludes> <sourceInclude>**/*.xml</sourceInclude> <sourceInclude>**/*.jsp</sourceInclude> </sourceIncludes> <additionalConfig> <file> <name>.settings/org.eclipse.core.resources.prefs</name> <content> <![CDATA[eclipse.preferences.version=1${line.separator}encoding/<project>=${project.build.sourceEncoding}${line.separator}]]> </content> </file> </additionalConfig> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> </configuration> </plugin> <!-- tomcat6插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat6-maven-plugin</artifactId> <version>${tomcat.version}</version> <configuration> <port>${webserver.port}</port> <path>/${project.artifactId}</path> <uriEncoding>${project.build.sourceEncoding}</uriEncoding> </configuration> </plugin> <!-- tomcat7插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>${tomcat.version}</version> <configuration> <port>${webserver.port}</port> <path>/${project.artifactId}</path> <uriEncoding>${project.build.sourceEncoding}</uriEncoding> </configuration> </plugin> <!-- jetty插件 --> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>${jetty.version}</version> <configuration> <connectors> <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector"> <port>${webserver.port}</port> </connector> </connectors> <webAppConfig> <contextPath>/${project.artifactId}</contextPath> </webAppConfig> <systemProperties> <systemProperty> <name>org.mortbay.util.URI.charset</name> <value>${project.build.sourceEncoding}</value> </systemProperty> </systemProperties> </configuration> </plugin> <!-- resource插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> </plugin> <!-- install插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> <version>2.4</version> </plugin> <!-- clean插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.5</version> </plugin> <!-- ant插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> </plugin> <!-- dependency插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.5.1</version> </plugin> </plugins> </build> <profiles> <!-- 初始化數據庫 --> <profile> <id>init-db</id> <dependencies> <dependency> <groupId>org.dbunit</groupId> <artifactId>dbunit</artifactId> <version>2.4.8</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.2-FINAL</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> <configuration> <target> <!-- mysql --> <property name="dbunit.datatype" value="org.dbunit.ext.mysql.MySqlDataTypeFactory" /> <!-- oracle <property name="dbunit.datatype" value="org.dbunit.ext.oracle.Oracle10DataTypeFactory" /> --> <!-- mssql <property name="dbunit.datatype" value="org.dbunit.ext.mssql.MsSqlDataTypeFactory" /> --> <property file="src/main/resources/application.properties" /> <sql driver="${jdbc.driver}" url="${jdbc.url}" userid="${jdbc.username}" password="${jdbc.password}" onerror="continue" encoding="${project.build.sourceEncoding}"> <classpath refid="maven.test.classpath" /> <transaction src="db/sys/jeesite_${jdbc.type}.sql"/> <transaction src="db/cms/jeesite_${jdbc.type}.sql"/> <transaction src="db/oa/jeesite_${jdbc.type}.sql"/> <transaction src="db/prj/jeesite_${jdbc.type}.sql"/> <transaction src="db/act/drop/activiti.${jdbc.type}.drop.engine.sql"/> <transaction src="db/act/drop/activiti.${jdbc.type}.drop.history.sql"/> <transaction src="db/act/drop/activiti.${jdbc.type}.drop.identity.sql"/> <transaction src="db/act/create/activiti.${jdbc.type}.create.engine.sql"/> <transaction src="db/act/create/activiti.${jdbc.type}.create.history.sql"/> <transaction src="db/act/create/activiti.${jdbc.type}.create.identity.sql"/> </sql> <taskdef name="dbunit" classname="org.dbunit.ant.DbUnitTask" classpathref="maven.test.classpath" /> <!-- mysql、mssql --> <dbunit driver="${jdbc.driver}" url="${jdbc.url}" userid="${jdbc.username}" password="${jdbc.password}"> <!-- oracle <dbunit driver="${jdbc.driver}" url="${jdbc.url}" userid="${jdbc.username}" password="${jdbc.password}" schema="${jdbc.username}" > --> <dbconfig> <property name="datatypeFactory" value="${dbunit.datatype}" /> </dbconfig> <classpath refid="maven.test.classpath" /> <operation type="INSERT" src="db/sys/jeesite_data.xls" format="xls" transaction="true"/> <operation type="INSERT" src="db/cms/jeesite_data.xls" format="xls" transaction="true"/> <operation type="INSERT" src="db/oa/jeesite_data.xls" format="xls" transaction="true"/> </dbunit> </target> </configuration> </plugin> </plugins> </build> </profile> <!-- 生成自定義代碼 --> <profile> <id>code-gen</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> <configuration> <target> <echo message="Code Generate" /> <java classname="com.hellobike.zhangjianan.generate.Generate"> <classpath refid="maven.runtime.classpath"/> </java> </target> </configuration> </plugin> </plugins> </build> </profile> </profiles> <!-- 開發者信息 --> <developers> <developer> <id>thinkgem</id> <name>ZhangJiaNan</name> <email>thinkgem at 163.com</email> <roles><role>Project lead</role></roles> <timezone>+8</timezone> </developer> </developers> </project>
SpringMVC配置文件裏面必須有這個beanweb
<!-- 上傳文件攔截,設置最大上傳文件大小 10M=10*1024*1024(B)=10485760 bytes --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760" /> </bean>
form裏面必須有 enctype="multipart/form-data"spring
<form:form id="inputForm" modelAttribute="hotel" action="${ctx}/frontsite/hotel/save" method="post" enctype="multipart/form-data" class="form-horizontal"> <form:hidden path="id" /> <tags:message content="${message}" /> <div class="control-group"> <label class="control-label" for="value">名稱:</label> <div class="controls"> <form:input path="name" htmlEscape="false" maxlength="50" class="required" /> </div> </div> <!-- 其餘的一些表單域,在此省略 --> . . . . . . <div class="control-group"> <label class="control-label" for="sort">圖片:</label> <div class="controls"> <!--input-group start--> <div id="preview"> <c:if test="${hotel.id == null}"> <img id="imghead" border="0" src="${ctxStatic}/images/photo_icon.png" width="90" height="90" onclick="$('#picture').click();"> </c:if> <c:if test="${hotel.id != null}"> <img id="imghead" border="0" src="${ctx}/frontsite/hotel/getPhotoBlob?id=${hotel.id}" width="90" height="90" onclick="$('#picture').click();"> </c:if> </div> <form:input path="picture" type="file" onchange="previewImage(this)" style="display: none;" /> <!--input-group end--> </div> </div> <div class="form-actions"> <input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存" /> <input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)" /> </div> </form:form>
Controller裏面保存數據的方法必須這樣寫:sql
目的就是把MultipartHttpServletRequest和HttpServletRequest 分開處理數據庫
@RequiresPermissions("frontsite:hotel:view") @RequestMapping(value = "save") public String save(HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) { Hotel hotel = null; if(StringUtils.isNotBlank(request.getParameter("id"))){ hotel = hotelService.get(Long.valueOf(request.getParameter("id"))); }else{ hotel = new Hotel(); } if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap(); for(Map.Entry<String, MultipartFile> entry : fileMap.entrySet()){ // 對文件進處理 System.out.println(entry.getKey() + ":" + entry.getValue().getOriginalFilename()); try { hotel.setPicture(entry.getValue().getBytes()); } catch (IOException e) { e.printStackTrace(); } } hotel.setName(request.getParameter("name")); hotel.setInfo(request.getParameter("info")); hotel.setAddress(request.getParameter("address")); hotel.setPrice(new BigDecimal(request.getParameter("price"))); hotel.setPhone(request.getParameter("phone")); hotel.setCountry(request.getParameter("country")); hotel.setProvince(request.getParameter("province")); hotel.setCity(request.getParameter("city")); hotel.setArea(request.getParameter("area")); } hotelService.save(hotel); return "redirect:" + Global.getAdminPath() + "/frontsite/hotel/"; }
前三個要素知足了,保存文件到數據庫的longBlob字段就沒問題了
可是要想在編輯頁面把圖片回顯出來,還須要下功夫,見以下jsp代碼
//代碼說明:新增頁面和修改頁面分開來處理,用<c:if判斷,關鍵是用src="XXXX"指向一個專門獲取圖片的controller方法 <div class="control-group"> <label class="control-label" for="sort">圖片:</label> <div class="controls"> <!--input-group start--> <div id="preview"> <c:if test="${hotel.id == null}"> <img id="imghead" border="0" src="${ctxStatic}/images/photo_icon.png" width="90" height="90" onclick="$('#picture').click();"> </c:if> <c:if test="${hotel.id != null}"> <img id="imghead" border="0" src="${ctx}/frontsite/hotel/getPhotoBlob?id=${hotel.id}" width="90" height="90" onclick="$('#picture').click();"> </c:if> </div> <form:input path="picture" type="file" onchange="previewImage(this)" style="display: none;" /> <!--input-group end--> </div> </div>
上面這段代碼最關鍵的是
src="${ctxStatic}/images/photo_icon.png"
和這個代碼對應的Controller後臺的代碼以下:
@RequestMapping("getPhotoBlob") public void getPhotoBlob(Long id, HttpServletRequest request, HttpServletResponse response) { try { // blob就是你要顯示的那張圖片 byte[] data = hotelService.findPictureById(id); OutputStream out = response.getOutputStream(); response.setContentType("image/png"); out.write(data); out.close(); } catch (Exception e) { e.printStackTrace(); } }
service層
public byte[] findPictureById(Long id) throws SQLException { return hotelDao.findPictureById(id); }
和DAO層:
public byte[] findPictureById(Long id) throws SQLException { ScenicSpot scenicSpot = getByHql("from ScenicSpot where id=:p1", new Parameter(id)); if (scenicSpot != null && scenicSpot.getPicture() != null) { return scenicSpot.getPicture(); } else { // 爲了防止頁面空指針 return "null".getBytes(); } }
添加頁面:
修改頁面回顯:
至此,大功告成
好人作到底,順便把文件上傳的控件代碼也提供一下,請叫我雷鋒:
<%@ page contentType="text/html;charset=UTF-8"%> <%@ include file="/WEB-INF/views/include/taglib.jsp"%> <html> <head> <title>酒店管理</title> <meta name="decorator" content="default" /> <script type="text/javascript"> $(document).ready(function() { $("#value").focus(); $("#inputForm").validate(); }); </script> </head> <body> <ul class="nav nav-tabs"> <li><a href="${ctx}/frontsite/hotel/">酒店列表</a></li> <li class="active"><a href="${ctx}/frontsite/hotel/form?id=${hotel.id}">酒店${not empty hotel.id?'修改':'添加'}</a></li> </ul> <br /> <form:form id="inputForm" modelAttribute="hotel" action="${ctx}/frontsite/hotel/save" method="post" enctype="multipart/form-data" class="form-horizontal"> <form:hidden path="id" /> <tags:message content="${message}" /> <div class="control-group"> <label class="control-label" for="value">名稱:</label> <div class="controls"> <form:input path="name" htmlEscape="false" maxlength="50" class="required" /> </div> </div> <div class="control-group"> <label class="control-label" for="label">描述信息:</label> <div class="controls"> <form:input path="info" htmlEscape="false" maxlength="50" class="required" /> </div> </div> <div class="control-group"> <label class="control-label" for="type">地址:</label> <div class="controls"> <form:input path="address" htmlEscape="false" maxlength="50" class="required" /> </div> </div> <div class="control-group"> <label class="control-label" for="description">價格:</label> <div class="controls"> <form:input path="price" htmlEscape="false" maxlength="50" class="required" /> </div> </div> <div class="control-group"> <label class="control-label" for="sort">電話:</label> <div class="controls"> <form:input path="phone" htmlEscape="false" maxlength="11" class="required" /> </div> </div> <div class="control-group"> <label class="control-label" for="sort">圖片:</label> <div class="controls"> <!--input-group start--> <div id="preview"> <c:if test="${hotel.id == null}"> <img id="imghead" border="0" src="${ctxStatic}/images/photo_icon.png" width="90" height="90" onclick="$('#picture').click();"> </c:if> <c:if test="${hotel.id != null}"> <img id="imghead" border="0" src="${ctx}/frontsite/hotel/getPhotoBlob?id=${hotel.id}" width="90" height="90" onclick="$('#picture').click();"> </c:if> </div> <form:input path="picture" type="file" onchange="previewImage(this)" style="display: none;" /> <!--input-group end--> </div> </div> <div class="control-group"> <label class="control-label" for="sort">國家:</label> <div class="controls"> <form:input path="country" htmlEscape="false" maxlength="11" class="required" /> </div> </div> <div class="control-group"> <label class="control-label" for="sort">省:</label> <div class="controls"> <form:input path="province" htmlEscape="false" maxlength="11" class="required" /> </div> </div> <div class="control-group"> <label class="control-label" for="sort">市:</label> <div class="controls"> <form:input path="city" htmlEscape="false" maxlength="11" class="required" /> </div> </div> <div class="control-group"> <label class="control-label" for="sort">區:</label> <div class="controls"> <form:input path="area" htmlEscape="false" maxlength="11" class="required" /> </div> </div> <div class="form-actions"> <input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存" /> <input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)" /> </div> </form:form> <script type="text/javascript"> //圖片上傳預覽 IE是用了濾鏡。 function previewImage(file) { var MAXWIDTH = 180; var MAXHEIGHT = 180; var div = document.getElementById('preview'); if (file.files && file.files[0]) { div.innerHTML = '<img id=imghead onclick=$("#picture").click()>'; var img = document.getElementById('imghead'); img.onload = function() { var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight); img.width = rect.width; img.height = rect.height; // img.style.marginLeft = rect.left+'px'; img.style.marginTop = rect.top + 'px'; } var reader = new FileReader(); reader.onload = function(evt) { img.src = evt.target.result; } reader.readAsDataURL(file.files[0]); } else //兼容IE { var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="'; file.select(); var src = document.selection.createRange().text; div.innerHTML = '<img id=imghead>'; var img = document.getElementById('imghead'); img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src; var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight); status = ('rect:' + rect.top + ',' + rect.left + ',' + rect.width + ',' + rect.height); div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sFilter+src+"\"'></div>"; } } function clacImgZoomParam(maxWidth, maxHeight, width, height) { var param = { top : 0, left : 0, width : width, height : height }; if (width > maxWidth || height > maxHeight) { rateWidth = width / maxWidth; rateHeight = height / maxHeight; if (rateWidth > rateHeight) { param.width = maxWidth; param.height = Math.round(height / rateWidth); } else { param.width = Math.round(width / rateHeight); param.height = maxHeight; } } param.left = Math.round((maxWidth - param.width) / 2); param.top = Math.round((maxHeight - param.height) / 2); return param; } </script> </body> </html>