springmvc图片上传

在 页面form中提交enctype="multipart/form-data"的数据时,需要springmvc对multipart类型的数据进行解析。

在springmvc.xml中配置multipart类型解析器。

1     <!-- 文件上传 -->
2      <bean id="multipartResolver"
3         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4         <!-- 设置上传文件的最大尺寸为5MB -->
5         <property name="maxUploadSize">
6             <value>5242880</value>
7         </property>
8     </bean>

创建图片虚拟 目录 存储图片

注意:在图片虚拟目录 中,一定将图片目录分级创建(提高i/o性能),一般我们采用按日期(年、月、日)进行分级创建。

 1 <tr>
 2     <td>商品图片</td>
 3     <td>
 4         <c:if test="${itemsCustom.pic !=null}">
 5             <img src="/pic/${itemsCustom.pic}" width=100 height=100/>
 6             <br/>
 7         </c:if>
 8         <input type="file"  name="items_pic"/> 
 9     </td>
10 </tr>

修改:商品修改controller方法:

 1 //拿到图片的原始名称
 2         String originalFilename = items_pic.getOriginalFilename();
 3         //上传图片
 4         if(items_pic!=null && originalFilename!=null && originalFilename.length()>0){
 5             String pic_path = "F:\sshimg\";
 6             
 7             //新的图片名称
 8             String newFileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
 9             File newFile = new File(pic_path+newFileName);
10             //将内存中的数据写入磁盘
11             items_pic.transferTo(newFile);
12             //将新的图片名称写入到itemsCustom中
13             itemsCustom.setPic(newFileName);
14         }
原文地址:https://www.cnblogs.com/cuibin/p/6880255.html