Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to display an uploaded picture (which is now a byte array) on a jsp page. Now, the byte[] column exists in the database and has to be converted to an image.

This is what I've been trying:

Part of the table on jsp page:

<c:forEach var="user" items="${userList}">
    <tr>
        <td>${user.fileName}</td>
        <td>
            <img src="data:image/jpg;base64,${user.imageFile}" alt="No image">
        </td>

Part of the controller that takes an array of bytes from a MultipartFile object:

@RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView userRegister(@ModelAttribute("user") @Valid User user, BindingResult result, ModelMap model, @RequestParam("fileData") MultipartFile fileData) throws Exception {

            if (!fileData.isEmpty() && fileData != null) {                

                byte[] bytes = fileData.getBytes();
                user.setFileName(fileData.getOriginalFilename());
                user.setImageFile(bytes);
            }
        }

If any additional information is needed, please let me know. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can add a tranisent base64imageFile property to your User. It will hold the base64 encoded string of the image, which you can access in your jsp like

<img alt="img" src="data:image/jpeg;base64,${user.base64imageFile}"/>

And in your method you should do the encoding, somethig like

@RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView userRegister(@ModelAttribute("user") @Valid User user, BindingResult result, ModelMap model, @RequestParam("fileData") MultipartFile fileData) throws Exception {
        if (!fileData.isEmpty() && fileData != null) {                
            byte[] bytes = fileData.getBytes();
            user.setFileName(fileData.getOriginalFilename());
            user.setImageFile(bytes);
            byte[] encodeBase64 = Base64.encodeBase64(bytes);
            String base64Encoded = new String(encodeBase64, "UTF-8");
            user.setBase64image(base64encoded);
        }
    }

IOUtils and Base64 are a handy util classes from org.apache.commons, shouldn't have a problem finding


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...