關於更新用戶信息丟失頭像的問題

本人在設置頭像上傳更新的時候,發現有個更新的BUG,上傳好之後也能顯示出來,但是這個時候點擊更新,沒有重新上傳圖片,就出來了頭像丟失的問題。後來發現controller判斷頭像是否爲空出現了問題
原本判斷是 if(file!=null),原本是想判斷file是否爲空就可以知道修改的時候有沒有更改頭像,如果不爲空則證明更改了頭像,那麼後面就是添加頭像的操作了。
然而關鍵就在這裏,其實這個判斷有問題,這樣判斷是沒法判斷出file到底改變了沒有,也就是說即使沒有更改頭像,它也會認爲這個地方不爲空。
所以我就更改了這個判斷語句,if(!file.isEmpty())同時sql語句也使用了動態sql語句

<update id="update" parameterType="User">
        update user set 
        u_password=#{uPassword},
        u_name=#{uName},
        u_tel=#{uTel},
        u_email=#{uEmail},
        <if test="uPhoto!=null">u_photo=#{uPhoto}</if>
        where u_id=#{uId}
    </update>

附controller修改頭像的源碼:

@RequestMapping(value="/user/update.action",method={RequestMethod.POST})
    public String update(User user,HttpServletRequest request,
            @RequestParam("photo") MultipartFile file){
        //1.判斷上傳的頭像是否爲空
        if(!file.isEmpty()){
            //頭像上傳
            //2、指定上傳目錄
            String str=request.getServletContext().getRealPath("//upload//user");
            System.out.println(str);
            //3、如果路徑不存在,創建此路徑
            File path=new File(str);
            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
            user.setuPhoto("user//"+name);
            }
        userService.update(user);
        //數據在session中,修改之後需要刷新session裏面的值
        User user1=userService.findUser_Class(user.getuId());
        request.getSession().setAttribute("user_class", user1);
        return "kstj/kstj";
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章