SprimgMVC学习笔记(七)—— 上传图片

1、配置虚拟目录

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

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

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

  也能够经过eclipse配置,以下图:浏览器

  

  

  复制一张图片到存放图片的文件夹,使用浏览器访问tomcat

  测试效果,以下图:mvc

  

 

  idea设置tomcat虚拟路径的两种方法app

2、加入jar包

  

3、配置上传解析器

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

  <!-- 文件上传,id必须设置为multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置文件上传大小 -->
        <property name="maxUploadSize" value="5000000"></property>
    </bean>

4、修改jsp页面

  修改itemEdit.jsp:eclipse

  

  

5、实现图片上传

  在更新商品方法中添加图片上传逻辑jsp

/** * 更新商品 * * @param item * @return * @throws Exception */ @RequestMapping("updateItem") public String updateItemById(Item item, MultipartFile pictureFile) throws Exception { // 图片上传 // 设置图片名称,不能重复,能够使用uuid
    String picName = UUID.randomUUID().toString(); // 获取文件名
    String oriName = pictureFile.getOriginalFilename(); // 获取图片后缀
    String extName = oriName.substring(oriName.lastIndexOf(".")); // 开始上传
    pictureFile.transferTo(new File("C:/upload/image/" + picName + extName)); // 设置图片名到商品中
    item.setPic(picName + extName); // --------------------------------------------- // 更新商品
    this.itemService.updateItemById(item); return "forward:/itemEdit.action"; }

  效果以下:ide

  

相关文章
相关标签/搜索