Spring MVC图片上传

  1. 配置虚拟目录
  2. 导入jar包(commons-fileupload和commons-io包)
  3. 在springmvc.xml中配置上传解析器
  4. 前端页面的修改
  5. 书写文件上传方法(参数类型为MultipartFile)

具体细节

1. 在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:

<Context docBase="D:\develop\upload" path="/upload" reloadable="false"/>  

2.

<!-- 文件上传解析器,id名称一定为multipartResolver -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- 设定默认编码 -->

<property name="defaultEncoding" value="UTF-8"></property>

<!-- 可对文件上传大小做限制,具体属性可以查看 如5M=1024*1024*5-->

<property name="maxUploadSize" value="5242880"></property>

</bean>

3.

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

<!-- 另外,form表单处还要设置 enctype="multipart/form-data" --!>

<form id="itemForm" action="${pageContext.request.contextPath}/updateItem" method="post" enctype="multipart/form-data">

  5.

@RequestMapping(value = {"/updateItem"})
    //pictureFile要和前端name属性同名!!!
    public String updateItem(Items item, MultipartFile pictureFile) throws IllegalStateException, IOException {
        //使用uuid为命名防止文件名重复
        String uuidName = UUID.randomUUID().toString();
        uuidName = uuidName.replaceAll("-", "");
        //获取文件名
        String originalFilename = pictureFile.getOriginalFilename();
        //获取文件名后缀
        String pexfix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
        //文件上传方法,设置上传的路径,并拼接文件名和后缀
        pictureFile.transferTo(new File("/Users/fatah/Desktop/upload/" + uuidName + pexfix));
        //文件已上传到服务器指定位置,将文件名保存到数据库字段中
        item.setPic(uuidName + pexfix);
        //执行更新操作
        this.itemsService.toUpdate(item);
        return "redirect:/itemEdit?id=" + item.getId();
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值