頭像上傳與顯示 SpringBoot


頭像上傳與顯示

Controller

  • 形參的名字不要變
  • 最關鍵是uploadFile.transferTo(),使文件上傳簡便了許多
  • 上傳文件后存入數據庫,我加了一個/img/,因為我是存在服務器中的img路徑下的,記得在項目中一定要先創建一個img,
    其實不我怎么懂服務器和我IDEA中項目到底怎樣的關系。我抱着試一試的態度,發現創建了一個img后,上傳的內容也可以從這兒取到,
    所以才在數據庫中存入地址中加了img,到時候在前端中可以直接
    src="/img/..."

image.png

//文件上傳
    @RequestMapping("/up")
    public String up(MultipartFile uploadFile, HttpSession session) throws IOException {
        //獲取上傳文件名稱
        String fileName = uploadFile.getOriginalFilename();
        //uuid+后綴名,給文件重新取名
        String finalFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        //最后存儲的路徑,是本地的服務器中
        String path = session.getServletContext().getRealPath("img")+ File.separator + finalFileName;
        System.out.println(path);
        //上傳
        File file = new File(path);
        uploadFile.transferTo(file);

        //上傳成功后,將地址存入數據庫,讓前端可以直接拿圖片
        String idPic = "/img/" + finalFileName;
        User user = new User();
        user.setIdPic(idPic);
        //獲取id值
        user.setUserId(2);
        userService.updateUser(user);

        return "success";
    }

頁面

image.png

<form  action="/up" enctype="multipart/form-data" method="post" style="display: none;" id="show_up">
	<input type="file" name="uploadFile"/>
	<input type="submit"/>
</form>

頁面進階版(將form隱藏,通過單擊事件觸發)

image.png
image.png

Ajax

  • 將原來的圖片刪除,再添加進去
//個人基本資料回顯
function show_myself(){
    $.ajax({
        url: "/getUserById",
        type: "post",
        dataType: "json",
        success: function(userById){

            //獲取圖片路徑
            $(".logo").remove();
            var str = "<div class=\"logo\" style=\"background-image:url(&quot;"+ userById[0].idPic +"&quot;);\" data-v-8dc533f6>\n</div>";
            $("#insert_img").prepend(str);

        },
        error: function(){
            alert("Error");
        }
    })
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM