EchoDemo's Blogs

springmvc学习笔记(17)-上传图片

黄水塘里游着白鸭

高粱梗油青的刚高过头

这跳动的心怎样安插

田里一窄条路,八月里这忧愁?
天是昨夜雨洗过的,山岗

照着太阳又留一片影

羊跟着放羊的转进村庄

一大棵树荫下罩着井,又像是心!
从没有人说过八月什么话

夏天过去了,也不到秋天

但我望着田垄,土墙上的瓜

仍不明白生活同梦怎样的连牵

—-现代·林徽因《八月的忧愁》节选

springmvc中对多部件类型解析

在修改商品页面,添加上传商品图片功能。在页面form中提交enctype=”multipart/form-data”的数据时,需要springmvc对multipart类型的数据进行解析。通过在springmvc.xml中配置multipart类型解析器来完成。

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

加入上传图片的jar

(1)添加依赖

<!-- 文件上传 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

(2)依赖树

[INFO] \- commons-fileupload:commons-fileupload:jar:1.3.1:compile
[INFO]    \- commons-io:commons-io:jar:2.2:compile

可以看到,其实还间接依赖了commons-io:commons-io:jar。

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

直接修改tomcat的配置,在conf/server.xml文件,添加虚拟目录。

<Context docBase="图片存放的磁盘路径" path="/pic" reloadable="false"/>

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


上传图片代码

(1)页面

<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>

(2)controller方法

修改:商品修改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 {...}

(3)实现

// 原始名称
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);

}
🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------