簡體   English   中英

無法將圖像從數據庫加載到 thymleaf

[英]Cannot load the image from database to thymleaf

這是我的 editprofile.html:

<form th:action="@{/updateProfile}" method="post" class="signin-form" th:object="${editprofile}" enctype="multipart/form-data">
    <div class="title-main text-center mx-auto mb-md-5 mb-4" style="max-width:500px;">
        <h5 class="footer-title-29">Personal Details</h5>
        <div class="col-sm-6 profile_Pic">
            <img id="thumbnail" th:src="*{'data:image/jpg;base64,'+profile_pic}" width="200" />
        </div>
    </div>
    <br><br>
    <div class="input-grids">
        <label class="control-label" for="name">Name:</label>
        <input type="text" th:field="*{name}" id="name" class="contact-input" />
        <div class="row">
            <div class="col-sm-6">
                <label class="control-label" for="mobileNumber">Mobile Number:</label>
                <input type="text" th:field="*{mobileNumber}" id="mobileNumber" class="contact-input" />
            </div>
            <div class="col-sm-6">
                <label class="control-label" for="email">Email:</label>
                <input type="text" th:field="*{email}" id="email"
                                   class="contact-input" />
            </div>
        </div>
    </div>
    <div class="title-main text-center mx-auto mb-md-5 mb-4" style="max-width:500px;">
        <h5 class="footer-title-29">Address Details</h5>
    </div>
    <div class="input-grids">
        <label class="control-label" for="address1">Address Line 1:</label>
        <input type="text" th:field="*{address1}" id="address1" class="contact-input" />
        <label for="address2">Address Line 2:</label>
        <input type="text" th:field="*{address2}" id="address2" class="contact-input" />
        <label class="control-label" for="city">City:</label>
        <input type="text" th:field="*{city}" id="city" class="contact-input" />
        <div class="row">
            <div class="col-sm-6">
                <label class="control-label" for="state">State:</label>
                <input type="text" th:field="*{state}" id="state"
                                   class="contact-input" />
            </div>
            <div class="col-sm-6">
                <label class="control-label" for="zipCode">Zip Code:</label>
                <input type="text" th:field="*{zipCode}" id="zipCode"
                                   class="contact-input" />
            </div>
            <div class="col-sm-6">
                <label class="control-label" for="fileImage">Upload image</label>
                <input type="file" name="fileImage" accept="image/*" id="fileImage" />
            </div>
        </div>
    </div>
    <div class="col-md-8 login-center text-start">
        <button class="btn btn-style btn-style-3 text-left" >Update</button>
        <a th:href="@{/dashboard}" class="new-user text-right">
            <button class="btn btn-style btn-style-3 text-left" th:formaction="@{/displayProfile}">BACK</button></a>
    </div>
</form>

我在從數據庫中添加和檢索數據時進行了壓縮和解壓縮

代碼:ImageUtil.java

public static byte[] compressImage(byte[] data) {

        Deflater deflater = new Deflater();
        deflater.setLevel(Deflater.BEST_COMPRESSION);
        deflater.setInput(data);
        deflater.finish();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] tmp = new byte[1024];

        while (!deflater.finished()) {
            int size = deflater.deflate(tmp);
            outputStream.write(tmp, 0, size);
        }

        try {
            outputStream.close();
        } catch (Exception e) {
        }

        return outputStream.toByteArray();
    }

    public static byte[] decompressImage(byte[] data) {
        Inflater inflater = new Inflater();
        inflater.setInput(data);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] tmp = new byte[1024];

        try {
            while (!inflater.finished()) {
                int count = inflater.inflate(tmp);
                outputStream.write(tmp, 0, count);
            }
            outputStream.close();
        } catch (Exception exception) {
        }

        return outputStream.toByteArray();
    }

我上傳圖片如下:

person.getAddress().setProfile_pic(ImageUtil.compressImage(file.getBytes()));
  personRepository.save(person);

並且圖片成功保存到db

問題是圖像無法顯示。我在從數據庫中檢索數據時這樣做了:

byte[] decomImage = ImageUtil.decompressImage(person.getAddress().getProfile_pic());
byte[] encodeBase64 = Base64.getEncoder().encode(decomImage);
String base64Encoded = new String(encodeBase64, "UTF-8");

pojoprofile.setEncoded_image(base64Encoded);

我無法檢索圖像並顯示它。 我嘗試解壓縮圖像並將其轉換為 Base64 以將其顯示在 thymleaf 中。

這是我的 controller class 上傳圖片到數據庫:

 @RequestMapping(value = "/EditProfile")
    public ModelAndView EditProfile(Model model, HttpSession httpSession){
        PersonPojo person=(PersonPojo) httpSession.getAttribute("loggedInPerson");
        Profile pojoprofile1=new Profile();
        pojoprofile1.setName(person.getName());
        pojoprofile1.setEmail(person.getEmail());
        pojoprofile1.setMobileNumber(person.getMobileNumber());
        if(person.getAddress()!=null&&person.getAddress().getAddressId()>0){
            pojoprofile1.setAddress1(person.getAddress().getAddress1());
            pojoprofile1.setAddress2(person.getAddress().getAddress2());
            pojoprofile1.setCity(person.getAddress().getCity());
            pojoprofile1.setState(person.getAddress().getState());
            pojoprofile1.setZipCode(person.getAddress().getZip_code());
            pojoprofile1.setProfile_pic(Base64.getEncoder().encode(person.getAddress().getProfile_pic()));

//            pojoprofile1.setProfile_pic(person.getAddress().getProfile_pic());
        }
        ModelAndView editprofile=new ModelAndView("EditProfile.html");
        editprofile.addObject("editprofile",pojoprofile1);
        return editprofile;
    }


@RequestMapping(value = "/updateProfile")
    public String updateProfile(@RequestParam("fileImage") MultipartFile file, @Valid @ModelAttribute("editprofile") Profile profile, Errors errors,
                                HttpSession httpSession) throws IOException {
if(errors.hasErrors()){
 return "EditProfile.html";
    }
   PersonPojo person=(PersonPojo) httpSession.getAttribute("loggedInPerson");
    person.setName(profile.getName());
    person.setEmail(profile.getEmail());
   person.setMobileNumber(profile.getMobileNumber());
   if(person.getAddress() == null || !(person.getAddress().getAddressId()>0)){
            person.setAddress(new AddressPoJO());
        }
        person.getAddress().setAddress1(profile.getAddress1());
        person.getAddress().setAddress2(profile.getAddress2());
        person.getAddress().setCity(profile.getCity());
        person.getAddress().setState(profile.getState());
        person.getAddress().setZip_code(profile.getZipCode());
        person.getAddress().setProfile_pic(ImageUtil.compressImage(file.getBytes()));
          personRepository.save(person);
        httpSession.setAttribute("loggedInPerson", person);
        return "redirect:/dashboard";
    }

Controller 顯示個人資料頁面的內容:

@RequestMapping("/displayProfile")
public ModelAndView Myprofile(HttpSession httpSession) throws UnsupportedEncodingException {
    Profile pojoprofile=new Profile();
    PersonPojo person=(PersonPojo) httpSession.getAttribute("loggedInPerson");
    pojoprofile.setName(person.getName());
    pojoprofile.setEmail(person.getEmail());
    pojoprofile.setMobileNumber(person.getMobileNumber());
    if(person.getAddress()!=null&&person.getAddress().getAddressId()>0){
        log.info("Inside the if"+new MyProfile().getClass().toString());
        pojoprofile.setAddress1(person.getAddress().getAddress1());
        pojoprofile.setAddress2(person.getAddress().getAddress2());
        pojoprofile.setCity(person.getAddress().getCity());
        pojoprofile.setState(person.getAddress().getState());
        pojoprofile.setZipCode(person.getAddress().getZip_code());
        byte[] encodeBase64 = Base64.getEncoder().encode(ImageUtil.decompressImage(person.getAddress().getProfile_pic()));
        pojoprofile.setProfile_pic(encodeBase64);
    }else {
        pojoprofile.setAddress1(" Not available ");
        pojoprofile.setAddress2(" Not Available");
        pojoprofile.setZipCode(" Not Available");
        pojoprofile.setState(" Not Available");
        pojoprofile.setCity(" Not Available");
    }

    return new ModelAndView("profile.html").addObject("profile",pojoprofile);
}

您應該返回圖像的字符串表示形式,而不是字節數組。 所以將您的代碼更改為

 String encodeBase64 =   Base64.getEncoder().encodeToString(person.getAddress().getProfilePic());

pojoprofile.setProfilePic(encodeBase64);

這意味着 Profile.profilePic 也是一個字符串。 person.getAddress().getProfilePic()應該返回一個有效的字節數組)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM