原文地址:http://www.cnblogs.com/xing901022/p/6107048.html
最近工作遇到一个需求,需要下载excel模板,编辑后上传解析存储到数据库。因此为了更好的理解公司框架,我就自己先用spring mvc实现了一个样例。
之前曾经介绍过一个最简单的spring mvc的项目如何搭建,传送门在这里。
这次就基于这个工程,继续实现上传下载的小例子。需要做下面的事情:
1 增加index.html,添加form提交文件2 引入commons-fileupload、commons-io、jxl等工具包3 创建upload download接口4 注入multipartResolver bean5 在upload中使用HttpServletRequest获取文件流,通过WorkBook进行解析6 在download中通过HttpServerResponse返回文件流,实现下载页面很简单,其实就是一个form标签,需要注意的是:
form中enctype="multipart/form-data"action指定访问的urlinput中需要设置name属性,这样后端才能获取到文件对象 <form role="form" action="/upload" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="file">上传文件</label> <input type="file" id="file" name="file"> </div> <button type="submit" class="btn btn-default">提交</button> </form>涉及的jar包有:
commons-fileupload 用于获取上传文件jxl 用于解析excel <!-- springframework begins --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0-b01</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <!-- https://mvnrepository.com/artifact/jexcelapi/jxl --> <dependency> <groupId>jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6</version> </dependency>在web.xml中需要配置默认的访问页面,因为之前已经设置过拦截的请求是/,因此如果不设置所有的静态页面都会被拦截下来。
<welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list>在spring的配置文件中,加入CommonsMultipartResolver的bean。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- set the max upload size100MB --> <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean>有需要的可以拿去参考
网盘下载链接
分类: Java