#Springmvc 文件上传简介 使用servlet3 的 javax.servlet.http.Part API 接口实现文件上传。使用 multipart编码文件。html
默认在单个请求中,只处理每一个文件最大1Mb,最多10Mb的文件数据。java
你能够覆盖那些值,也能够设置临时文件存储的位置(好比,存储到/tmp文件夹下)及传递数据刷新到磁盘的阀值(经过使用MultipartProperties类暴露的属性)。git
若是你须要设置文件不受限制,能够设置spring.http.multipart.max-file-size属性值为-1。web
#项目实例spring
##需求:在修改商品页面添加修改商品信息功能数据库
##springmvc 对多部件内容的解析spring-mvc
1、在jsp页面配置enctype对多部件上传的支持mvc
<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data"> <input type="hidden" name="id" value="${itemsCustom.id }"/> 修改商品信息: <table width="100%" border=1>
2、在springmvc.xml中配置multipart解析器dom
<!-- 图片上传解析器--> <bean id="mulitpartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="MaxUploadSize"> <!-- 设为5M --> <value>5242880</value> </property> </bean>
3、建立图片的虚拟目录jsp
在conf/server.xml 中,添加 <Context docBase="物理目录" path="/pic" reloadable="false"/>
4、具体实现
springmvc.xml 文件的配置
<!-- 图片上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="MaxUploadSize"> <!-- 设为5M --> <value>5242880</value> </property> </bean>
editItems.jsp 的配置
<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data"> <tr> <td>商品图片</td> <td> <c:if test="${itemsCustom.pic !=null}"> <img src="/pic/${itemsCustom.pic}" width=160 height=200/> <br/> </c:if> <input type="file" name="items_pic"/> </td> </tr>
controller方法
public String editItemsSubmit(Model model, HttpServletRequest request, Integer id, @ModelAttribute("itemsCustom") @Validated(value = {ValidGroup1.class}) ItemsCustom itemsCustom, BindingResult bindingResult, MultipartFile items_pic)throws Exception { ... String originalFilename= items_pic.getOriginalFilename(); if (items_pic != null && originalFilename!=null && originalFilename.length()>0) { //图片的存储的物理路径 String pic_path="E:\\Zen-Events\\Pictures\\tmp"; //新的图片名称 String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); //新的图片存储地址 File newFile = new File(pic_path, newFileName); //将图片写入到磁盘中 items_pic.transferTo(newFile); //将图片名称写入到数据库对象中 itemsCustom.setPic(newFileName); }
5、我的理解
经过页面上传图片: <input type="file" name="items_pic"/>
在controller中: 上传组件的文件必须以 MultipartFile 这个类型来存储,以及传递处理数据。
由此,springmvc才 能够解析这个文件。