图片上传

作者: 常威爆打来福 | 来源:发表于2018-05-18 19:48 被阅读43次

一 创建图片虚拟目录

在上传图片之前,先要设置虚拟目录(以IDEA为例)

  • 打开工具栏的运行配置Edit Configurations
  • 添加物理目录和并设置虚拟目录路径
创建图片虚拟
创建图片虚拟
  • 添加img图片在img文件夹内


    在目录中放入图片
  • 测试


    测试

二 SpringMVC上传商品图片

1 添加依赖
<!-- 文件上传 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
2 springmvc配置
<!--文件上传 图片大小5M-->
    <bean id ="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>
3 form表单配置

在页面form中提交enctype="multipart/form-data"的数据时,需要springmvc对multipart类型的数据进行解析。在springmvc.xml中配置multipart类型解析器。

.......省略
<form action="${pageContext.request.contextPath}/items/editItemsSubmit.action" 
                        method="post" 
                       enctype="multipart/form-data">
.......省略
</form>
.......省略
4 controller层编辑
    @RequestMapping(value = "/editItemsSubmit")
    public String editItemsSubmit(Model model, Integer id,
                                  @Validated(value = ValidGroup1.class) ItemsCustom itemsCustom,
                                  BindingResult bindingResult,
                                  MultipartFile multipartFile) throws Exception {
        //异常处理
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                System.out.println(objectError.getDefaultMessage());
            }
            model.addAttribute("allErrors", allErrors);

            model.addAttribute("itemsCustom", itemsCustom);
            return "editItems";
        }
        //上传图片
        //获取文件原始名
        String originalFilename = multipartFile.getOriginalFilename();
        if (multipartFile != null && originalFilename!=null && originalFilename.length()>0 ){
            //存储图片物理物理路径
            String pic_path = "E:\\IdeaProjects\\ssm_itemsDemo\\pic\\";
            //新图片名称
            String newFileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
            //新图片
            File newFile = new File(pic_path+newFileName);
            //将内存中的数据写入磁盘
            multipartFile.transferTo(newFile);
            //将新图片名称写到itemsCustom
            itemsCustom.setPic(newFileName);

        }
        itemsService.updateItems(id, itemsCustom);
        return "success";
    }
5 页面配置
        <tr>
            <td>商品图片</td>
            <td>
                <c:if test="${itemsCustom.pic!=null}">
                    <img src="/pic/${itemsCustom.pic}" width="100px" height="100px"><br>
                </c:if>
                <input type="file" name="multipartFile"></td>
        </tr>
测试
数据库

相关文章

网友评论

    本文标题:图片上传

    本文链接:https://www.haomeiwen.com/subject/koqgdftx.html