SpringMVC(六)SpringMVC的图片上传

2019-04-15 14:40发布

  1. 配置虚拟目录
tomcat上配置图片虚拟目录,在tomcatconf/server.xml中添加:
访问http://localhost:8080/pic即可访问F:developupload emp下的图片。
也可以通过eclipse配置:

  1. jar
CommonsMultipartResolver解析器依赖commons-fileuploadcommons-io,加入如下jar包:
  1. 配置解析器
  • 配置在springMVC.xml下
    <bean id="multipartResolver"        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">              <property name="maxUploadSize">           <value>5242880value>       property>    bean>


  1. 图片上传
  • controller

//商品修改提交    @RequestMapping("/editItemSubmit")    public String editItemSubmit(Items items, MultipartFile pictureFile)throws Exception{              //原始文件名称       String pictureFile_name =  pictureFile.getOriginalFilename();       //新文件名称       String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf("."));              //上传图片       File uploadPic = new java.io.File("F:/develop/upload/temp/"+newFileName);              if(!uploadPic.exists()){           uploadPic.mkdirs();       }       //向磁盘写文件       pictureFile.transferTo(uploadPic);
.....

  • 页面:

form添加enctype="multipart/form-data"<form id="itemForm"action="${pageContext.request.contextPath }/item/editItemSubmit.action"       method="post" enctype="multipart/form-data">       <input type="hidden" name="pic" value="${item.pic }" />

注意:filenamecontroller形参一致:<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>