关于图片上传

来源:互联网 发布:爱淘宝0.2元红包链接 编辑:程序博客网 时间:2024/04/29 12:46

添加图片jsp

 <input type="file" name="phImage" value="phImage"/>

然后是controller

//添加临床视频    @RequestMapping(value="/addClinicVideo",method={RequestMethod.POST})    public String addClinicVideo(Clinicvideo clinicvideo,HttpServletRequest request            ,@RequestParam("phImage") MultipartFile file){        //1.判断上传的头像是否为空        if(!file.isEmpty()){            //头像上传            //2、指定上传目录            String str=request.getSession().getServletContext().getRealPath("\\upload");            System.out.println(str);            //3、如果路径不存在,创建此路径            File path=new File(str);            System.out.println("path="+path);            if(!path.exists()){                path.mkdirs();            }            //4、获取名字            String name=file.getOriginalFilename();            //5、防止名字重复            name=UUID.randomUUID()+name;            //6、拼接路径      路径加名字  文件            File desPath= new File(path, name);            //7、文件上传            try {                                            //要上传的路径 , 文件-------字节数组                FileUtils.writeByteArrayToFile(desPath, file.getBytes());            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            //8、把改路径设置到user里面数据库里D://xxxx//upload//user/xx.jpg            clinicvideo.setImage(name);            System.out.println(clinicvideo.getImage()+"数据库中路径");        }        clinicVideoService.add(clinicvideo);        return "redirect:/clinicVideo/findClinicVideo";    }

从代码中可以看出图片上传的路径为 项目webApp下的upload文件夹下,所以我需要再springmvc-action.xml中加入upload的资源路径映射

   <mvc:resources location="/upload/" mapping="/upload/**"/>

然后显示的图片

<!--如果没有图片给定个默认图片--><c:if test="${clinicVideo.image == null || clinicVideo.image  ==''}"><img  src="${pageContext.request.contextPath }/img/avatar_lg.png"  width="100px"  height="100px"> </c:if><!--显示图片--><c:if test="${clinicVideo.image != null && clinicVideo.image !=''}">                        <img class="img-thumbnail"                          src="${pageContext.request.contextPath}/upload/${clinicVideo.image}"                         width="100px" height="100px">                         </c:if>
原创粉丝点击