SpringMVC文件上传

1、配置文件的解析器

在springmvc的配置文件中配置文件的解析器。

<!--配置文件解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--设置上传图片的最大尺寸,设置为5M=5*1024*1024-->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>

2、加入文件上传所需要的jar包

3、在jsp页面加入图片上传组件

<tr>
                <td>商品图片:</td>
                <td>
                    <img src="/pic/${itemsExtend.pic}" alt="图片">
                    <br/>
                    <input type="file" name="item_pic">
                </td>
            </tr>

4、在controller页面进行文件上传的处理

@RequestMapping("/updateitems")
public String updateitems(Model model, Integer id, @Validated(value = {VaildatorGroup1.class}) ItemsCustom itemsExtend,
                          BindingResult bindingResult, MultipartFile item_pic) throws Exception{

    String pic_name = item_pic.getOriginalFilename();
    if(item_pic != null && pic_name != null && pic_name.length() >0){
        //物理路径
        String filePath = "E:\SpringMVC\SpringMVC3\pic\";
        //新的图片名称
        String new_pic_name = UUID.randomUUID().toString()+pic_name.substring(pic_name.lastIndexOf("."));
        //新图片
        File file = new File(filePath+new_pic_name);
        //上传到磁盘
        item_pic.transferTo(file);
        //将名称写入ItemsCustom
        itemsExtend.setPic(new_pic_name);
    }
原文地址:https://www.cnblogs.com/jack1995/p/7357601.html