标签: springmvcjava
[TOC]git
本文展现如何在springmvc中上传图片github
在修改商品页面,添加上传商品图片功能。web
在页面form中提交enctype="multipart/form-data"
的数据时,须要springmvc对multipart类型的数据进行解析。spring
在springmvc.xml中配置multipart类型解析器。tomcat
<!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为5MB --> <property name="maxUploadSize"> <value>5242880</value> </property> </bean>
添加依赖mvc
<!-- 文件上传 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
依赖树app
[INFO] \- commons-fileupload:commons-fileupload:jar:1.3.1:compile [INFO] \- commons-io:commons-io:jar:2.2:compile
能够看到,其实还间接依赖了commons-io:commons-io:jar
dom
参考我以前的博文jsp
也能够直接修改tomcat的配置,在conf/server.xml文件,添加虚拟目录.
注意:在图片虚拟目录中,必定将图片目录分级建立(提升i/o性能),通常咱们采用按日期(年、月、日)进行分级建立。
<tr> <td>商品图片</td> <td> <c:if test="${items.pic !=null}"> <img src="/pic/${items.pic}" width=100 height=100/> <br/> </c:if> <input type="file" name="items_pic"/> </td> </tr>
修改:商品修改controller方法:
@RequestMapping("/editItemsSubmit") public String editItemsSubmit( Model model, HttpServletRequest request, Integer id, @ModelAttribute("items") @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 = "D:\\tmp\\"; //新的图片名称 String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); //新图片 File newFile = new File(pic_path+newFileName); //将内存中的数据写入磁盘 items_pic.transferTo(newFile); //将新图片名称写到itemsCustom中 itemsCustom.setPic(newFileName); }