springmvc中使用上传头像

来源:互联网 发布:mac上弹钢琴的软件 编辑:程序博客网 时间:2024/04/29 11:50

上传头像等使用到的组件

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--  <property name="maxUploadSize" value="2048000"></property> -->
    </bean>


    @RequestMapping("/changePhoto")

    public ModelAndView uploadPhoto(MultipartFile filePhoto,HttpSession httpSession,HttpServletRequest request){
        Users user = (Users) httpSession.getAttribute("user");
        ServletContext context=httpSession.getServletContext();

        //上传路径 需注意,在tomcat中配置虚拟路径或者在其目录下的conf中的server.xml中的<Host>节点下配置

         //    <Context path="/项目名/虚拟的路径如pic,任何字符都可以" docBase="D:\upload\users\imgs"></Context>

       //当你在项目中使用/pic时,实际使用的是D:\upload\users\imgs

                String filePath="D:/upload/users/imgs/";    
                //获取图片原始名称
                String originalFilename=filePhoto.getOriginalFilename();
                //图片扩展名
                String types=originalFilename.substring(originalFilename.lastIndexOf(".")+1).toLowerCase();
        
            try {
                System.out.println(types);
                //以用户id加图片扩展名给图片命名
                String newFileName=user.getId()+originalFilename.substring(originalFilename.lastIndexOf("."));
                File file=new File(filePath+newFileName);
                //上传
                filePhoto.transferTo(file);
                //以80*80大小改变图片,此处使用thumbnailator-0.4.2.jar改变图片大小
                Thumbnails.of(file).size(80, 80).keepAspectRatio(false).toFile(file);
                userBiz.updatePhoto(user,newFileName);
                context.setAttribute("photo","photo");
                } catch (Exception e) {
                    e.printStackTrace();
                }           
        return new ModelAndView("/user/success");

    }


这里是前台jsp 

<form action="changePhoto" method="post" enctype="multipart/form-data"  onsubmit="return checkPhoto(this)">
    请选择头像:<input type="file" name="filePhoto" id="filesize">
    <input type="submit" value="上传">
</form>
<input type="hidden" id="photo" value="${applicationScope.photo}"/>
<input type="hidden" id="maxSize" value="${applicationScope.maxSize}"/>
<script>
function checkPhoto(myupload){
    var file=document.getElementById("filesize");
    var types=file.value.substr(file.value.lastIndexOf(".")+1).toLowerCase();
    if(file.value==""){        
        alert("请选择图片后上传");
        return false;
    }else if(types!="jpg" && types!="png" && types!="bmp"){
        alert("只能上传jpg,png,bmp格式的图片");
        return false;
    }
    
}
</script>


0 0