SpringMVC的文件上传

SpringMVC为文件上传提供了直接的支持,这种支持是即插即用的MultiPartResolver实现的,springmvc使用Apache Commons FileUpload技术实现了一个MultiPartResolver实现类:CommonsMultiPartResolver

文件上传的前端实现

<form action="${pageContext.request.contextPath }/updateItem.action"
        method="post" enctype="multipart/form-data">
        <input type="text" name="id" value="${item.id}" /><br /> <input
            type="text" name="name" value="${item.name}" /><br /> <input
            type="text" name="price" value="${item.price}" /><br /> <input
            type="text" name="detail" value="${item.detail}" /><br /> <input
            type="text" name="createtime"
            value='<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>' /><br />
        <c:if test="${item.pic != null }">
            <img src="/pic/${item.pic}" width="100px" height="100px"/>
        </c:if>
        <input type="file" name="pictureFile"/>
        <input type="submit" value="提交" />
    </form>

注意
method=”post”
enctype=”multipart/form-data”
input type=”file” name=”pictureFile”

文件上传的服务端的实现

@RequestMapping(value="/updateItem",method=RequestMethod.POST)
    public String updateItem(@ModelAttribute("id") Integer id,@ModelAttribute("item")Items itemcustomer,MultipartFile pictureFile) throws Exception{
        //a博客.png
        String originalFilename = pictureFile.getOriginalFilename();
        //找不到返回-1
        String extension = "";
        int extensionIndex = -1;
        //如果有文件的扩展名那么获取它
        if((extensionIndex=originalFilename.lastIndexOf('.'))!=-1){
            //IndexOutOfBoundsException - 
            //if beginIndex is negative or larger than the length of this String object.
            extension = originalFilename.substring(extensionIndex);
        }
        //存储到服务器端的文件名
        String pic = UUID.randomUUID().toString().replace("-", "")+extension;

        String filePath = "H:\\Picture";

        File file = new File(filePath+"\\"+pic);
        //将文件保存到服务器端
        pictureFile.transferTo(file);

        itemcustomer.setPic(pic);
        itemsService.updateItems(id,itemcustomer);
        return "redirect:queryItems.action";
    }

主要的类型MultipartFile

配置

springmvc上下文中默认没有装配MultiPartResolver,因此默认情况下不能处理文件上传,所以需要配置
一般我们使用CommonsMultiPartResolver

    <!-- 配置文件上传的解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的大小的最大值,单位bytes -->
        <property name="maxUploadSize" value="10485760" />
        <property name="defaultEncoding" value="utf-8" />
    </bean>

注意需要添加Apache Commons FileUpload组件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值