SpringMVC的文件上传

来源:互联网 发布:java nio 关闭连接 编辑:程序博客网 时间:2024/03/28 17:21

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

原创粉丝点击