springMVC文件上传

 

1.1. 配置虚拟目录

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

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

访问http://localhost:8080/pic即可访问D:\develop\upload\temp下的图片。

也可以通过eclipse配置,如下图:
图片
------------------------------------------------------------

1.2. 配置上传解析器

springmvc.xml中配置文件上传解析器

<!-- 文件上传,id必须设置为multipartResolver -->

<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- 设置文件上传大小 -->

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

</bean> 
---------------------------------------------------------

设置表单可以进行文件上传,如下图:

图片
---------------------------------------------------------------

@RequestMapping(value = "/updateitem.action")

// public ModelAndView updateitem(Items items){      这里名字得和jsp页面的name属性相同

public String updateitem(QueryVo vo,MultipartFile pictureFile) throws Exception{

 

//保存图片到 

String name = UUID.randomUUID().toString().replaceAll("-", "");

//jpg

String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());

 

pictureFile.transferTo(new File("D:\\upload\\" + name + "." + ext));

 

vo.getItems().setPic(name + "." + ext);

//修改

itemService.updateItemsById(vo.getItems());

 

// ModelAndView mav = new ModelAndView();

// mav.setViewName("success");

return "redirect:/itemEdit.action?id=" + vo.getItems().getId();

// return "forward:/item/itemlist.action";

 

 

}

--------------------------------------------------------------------------

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

posted @ 2018-02-25 13:10  1斑点  阅读(91)  评论(0编辑  收藏  举报