springmvc--文件上传/图片上传

环境配置:

springmvc.xml文件配置

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="10000000"/>
</bean>

 

 

jsp代码:

<tr>
            
            <td>
                <c:if test="${item.pic !=null}">
                    <img id="image"   src="/pic/${item.pic}" width=100 height=100 />
                    <br/>
                </c:if>
                <input type="file" value="${item.pic}"  name="pictureFile" onchange="submitImgSizeUpload()" />
                <input type="hidden" value="${item.pic}"  name="pictureFileName"/>
            </td>
</tr>

 

ajax表单提交:

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.js"></script>

    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.form.js"></script>

    <script type="text/javascript">
        function submitImgSizeUpload() {
            var option = {
          // 发送ajax请求 type:
"post", url: "${pageContext.request.contextPath}/items/uploadPic.do",
          // 返回json数据 dataType:
"json",
          // 成功的回调方法 success:
function (data) {
            // 设置图片的属性值 $(
"#image").attr("src","/pic/"+data.pic); //alert(data.pic);
            // 刷新当前页面
            
window.location.reload(true);
                }
            };

            $("#itemForm").ajaxSubmit(option)
        }
 </script>

控制层Java代码:


// 图片上传
@RequestMapping("uploadPic") public @ResponseBody Items uploadPic(MultipartFile pictureFile, Items items) throws IOException { String name = UUID.randomUUID().toString().replaceAll("-", ""); String originalFilename = pictureFile.getOriginalFilename(); // jpg String ext = FilenameUtils.getExtension(originalFilename); String fileName = name+"."+ext; pictureFile.transferTo(new File("e:/pic/"+fileName)); items.setPic(name+"."+ext); itemsService.saveOrUpdate(items); return items; }

// 提交的数据库,回到列表页面
@RequestMapping("saveOrUpdate",String pictureFileName)
public String saveOrUpdate(Items items) {
items.setPic(fileName);
itemsService.saveOrUpdate(items);
return "redirect:list.do";
}
 

 

posted on 2018-02-06 13:14  jovelove  阅读(162)  评论(0)    收藏  举报