ssm学习笔记——上传图片

一:环境

  1.导包

      commons-fileupload-1.2.2.jar

      commons-io-2.4.jar

二:上传图片

  1.一些说明

    1)虚拟访问路径

      是为了把图片放到Apach服务器项目以外的磁盘目录

    2)input的name要求

      name的值需要和Controller的MultipartFile的名称一致。当然也可以注解改名字。

    3)input的属性

      enctype="multipart/form-data"

    4)springmvc.xml配置实体类

      ·id是固定的

      ·可以在其中配置上传的一些条件

  2.实现

    1)设置虚拟访问路径

      

    2)Controller层实现代码

      

    @RequestMapping(value = "/updateitem.action")
    public ModelAndView update(Items items, MultipartFile pictureFile) throws IllegalStateException, IOException {
        ModelAndView mav = new ModelAndView();
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        String ext = FilenameUtils.getExtension(pictureFile.getName());
        items.setPic(name + "." + ext);
        pictureFile.transferTo(new File("D:\\Study\\upload\\" + name + "." + ext));
        service.update(items);
        mav.setViewName("success");
        return mav;
    }

    3)前端添加input提交文件

      

    <form id="itemForm"    action="${pageContext.request.contextPath }/updateitem.action" method="post" enctype="multipart/form-data">
        <input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
        <table width="100%" border=1>
            <tr>
                <td>商品名称</td>
                <td><input type="text" name="name" value="${item.name }" /></td>
            </tr>
            <tr>
                <td>商品价格</td>
                <td><input type="text" name="price" value="${item.price }" /></td>
            </tr>
            
            <tr>
                <td>商品生产日期</td>
                <td><input type="text" name="createtime"
                    value="${item.createtime}" /></td>
            </tr>
            <tr>
                <td>商品图片</td>
                <td>
                    <c:if test="${item.pic !=null}">
                        <img src="/pic/${item.pic}" width=100 height=100/>
                        <br/>
                    </c:if>
                    <input type="file"  name="pictureFile"/> 
                </td>
            </tr>
            <tr>
                <td>商品简介</td>
                <td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="提交" />
                </td>
            </tr>
        </table>

    </form>
View Code

    4)springmvc.xml中配置实现类

    

        <!-- 配置文件上传类 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 上传图片的大小   B   5M  1*1024*1024*5-->
            <property name="maxUploadSize" value="5000000"/>
        </bean>

猜你喜欢

转载自www.cnblogs.com/Dbbf/p/9893387.html
今日推荐