JSP,JavaScript:将byte []显示为图像 [英] JSP, JavaScript: display byte[] as image

查看:141
本文介绍了JSP,JavaScript:将byte []显示为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码段从文件中选择和读取图像:

I am using the following snippet to select and read images from file:

<div class="col-md-6 form-group">
<input type='file' name="image" onchange="readURL(this);"
                    class="form-control" /> 
<img id="userimg" src="#" alt="" />
</div>

.js:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#userimg')
                .attr('src', e.target.result)
                .width(150)
                .height(200);
        };

        reader.readAsDataURL(input.files[0]);
    }
}

在我的servlet中,我将文件转换为byte[]:

In my servlet I convert the file to a byte[]:

(request.getParameter("image")).getBytes()

并将其插入数据库中.

然后,我尝试从数据库中读取它,并显​​示在.jsp页面中,如下所示:

Then, I try to read it from the database and display in a .jsp page, like this:

.jsp

  <div class="panel panel-success">
                        <h2>Pictures</h2>
                        <%
                            List<byte[]> pics = PictureTable.getConcertPictures(concertBean.getId());
                        %>
                        <%
                            for (byte[] p : pics) {
                                String encoded = ImageHelper.encodeImage(p);
                        %>
                        <img src="data:image/jpg;base64,<%=encoded%>">
                        <%
                            }
                        %>
    </div>

ImageHelper.java:

ImageHelper.java:

public static String encodeImage(byte[] img) {
        return Base64.encode(img);
    }

但是图像显示不正确 (某些东西确实插入了数据库).

but the image is not displayed correctly (something does get inserted into the database).

我已经修改了代码:

.jsp:

<div class="comments">
                <div class="panel panel-success">
                    <h2>Pictures</h2>
                    <%
                        List<byte[]> pics = PictureTable.getConcertPictures(concertBean.getId());
                    %>
                    <%
                        for (byte[] p : pics) {
                            String encoded = ImageHelper.encodeImage(p);
                    %>
                    <img src="data:image/jpg;base64,<%=encoded%>">
                    <%
                        }
                    %>
                </div>
                <!-- /container -->
                <form
                    action="GalleryController?action=add_concert_picture&concertID=<%=concertBean.getId()%>"
                    method="post" class="panel panel-success"
                    enctype="multipart/form-data">
                    <div class="col-md-6 form-group">
                        <input type='file' name="image" class="form-control" />
                    </div>
                    <button type="submit" class="btn">Submit</button>
                </form>
            </div>

servlet:

Part filePart = request.getPart("image");
InputStream fileContent = filePart.getInputStream();
PictureTable.insertConcertPicture(cid, user.getUser().getId(), fileContent);

PictureTable.java:

PictureTable.java:

public static void insertConcertPicture(int concertId, int userId, InputStream photo) {
        try (Connection connection = ConnectionPool.getConnectionPool().checkOut()) {

            PreparedStatement ps = connection
                    .prepareStatement("INSERT INTO concertphototable(ConcertId, UserId, Photo) VALUES(?,?,?)");

            ...
            ps.setBinaryStream(3, photo);

            ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

图像仍无法正确显示,但是现在页面的提交"部分甚至不可见.

The image is still not shown correctly, but now the "submit" part of the page is not even visible.

推荐答案

有很多方法可以做到这一点.我将返回base64 String并将其存储在数据库中.然后,您可以将其返回给JSP进行渲染.

There are many ways to do this. I would go by returning base64 String and store it in the database. Then you can return it to the JSP to render it.

为此,您必须:

<input type="file" name="file" onchange="encodeImageFileAsURL(this)" />
<form method="POST" action="/upload">
    <input id="image" type="text" name="image" value="asdf" /><br />
    <br /> <input type="submit" value="Submit" />
</form>
<script type="text/javascript">
    function encodeImageFileAsURL(element) {
        var file = element.files[0];
        var reader = new FileReader();
        reader.onloadend = function() {
            document.getElementById("image").value = reader.result;
        }
        reader.readAsDataURL(file);
    }
</script>

在您的/upload控制器中:

In your /upload controller:

@PostMapping("/upload")
public ModelAndView singleFileUpload(@RequestParam("image") String image, RedirectAttributes redir) {
    jdbcTemplate.update("INSERT INTO concertphototable(ConcertId, UserId, Photo) VALUES(?, ?, ?)", 1, 1, image);
    String imageString = jdbcTemplate.queryForObject("Select Photo from concertphototable where ConcertId = " + 1,
            String.class);
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("redirect:uploadStatus");
    redir.addFlashAttribute("image", imageString);
    return modelAndView;
}

然后转到uploadStatus页面:

And then to the uploadStatus page:

<img src=${image}>

不要对Spring部分感到困惑,您应该记住,必须将base64字符串从jsp发送到服务器,然后将其存储.然后,将其检索为String并将其传递给image src标记中的jsp,将显示该图像.如果没有特殊原因需要将图像作为Blob存储到数据库,则必须按照上述方法进行操作.

Don't get confused of the Spring part you should have in mind that you have to post the base64 String from jsp to server then store it. Then you retrieve it as String and pass it to the jsp in the image src tag and the image will be displayed. If there is no specific reason for you to store the image as blob to the database you have to go with the way above.

这篇关于JSP,JavaScript:将byte []显示为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆