在BLOB mysql中上传byte []似乎被砍掉了,为什么?

时间:2017-11-12 00:21:30

标签: java mysql jdbc blob

大家好,你怎么做:

我试图通过enctype =" multipart / form-data"上传图片到mysql行,我得到了奇怪的结果:

查看映像的Java JSP:

 <a href="viewevent?id=<%= viewevent.getId()%>">
    <img alt="" class="img-responsive image1" src="ViewImage?id=<%= viewevent.getId() %>">
 </a>

用于查看图像的Java ViewImage servlet方法:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String id = request.getParameter("id");

    DataAccess bd = new DataAccess();
    bd.openConnection();
    ResultSet rs = bd.exQuery("SELECT * FROM eventos WHERE id="+id , "SELECT");

    try{
        while(rs.next()){
            response.setContentType("image/png");
            System.out.println(rs.getBytes("foto"));
            response.getOutputStream().write(rs.getBytes("foto"));

            response.reset();
            response.setContentType("image/png");
            // Write image content to response.
            response.getOutputStream().write(rs.getBytes("foto"));
        }
        bd.closeConnection();
    }catch(Exception e){
        System.out.println("Error cogiendo foto");
    }



}

用于上传图片的Java JSP:

                    <form action="addevent" method="post" enctype="multipart/form-data">
                        ...
                        <div class="form-group">
                            <label for="foto">Image</label>
                            <input name="foto" id="imagen" type=file accept=".jpg, .jpeg, .png">                                 
                        </div>                          
                       ...
                    </form>

用于上传图片的addevent servlet代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    ...
    Part foto = request.getPart("foto");
    ...
    byte[] data = new byte[(int) foto.getSize()];
    foto.getInputStream().read(data, 0, data.length);

    bd.exQuery("UPDATE eventos SET foto = '"+data+"' WHERE titulo='"+titulo+"';", "UPDATE");
    bd.closeConnection();
...

}

当我从MySQL保存BLOB文件作为txt文件时,我得到以下内容:

[B@2a83de12 
[B@3d00eeab
...

正如你所知,当我将它们保存为txt时,我只会得到一些字符...使用此代码我无法上传图像并在src上查看它们。我不知道我做错了什么,但这不会工作......

提前致谢!

1 个答案:

答案 0 :(得分:4)

bd.exQuery("UPDATE eventos SET foto = '"+data+"' WHERE titulo='"+titulo+"';", "UPDATE");

问题出在这里。您正在执行SQL字符串连接,它会调用byte[].toString(),从而产生[B@2a83de12之类的结果。您应该使用带有参数标记的预准备语句,并通过参数为预准备语句提供BLOB:

PreparedStatement ps = conn.prepareStatement("UPDATE eventos SET foto = ? WHERE titulo=?");
ps.setObject(1, data);
ps.setObject(2, titulo);
int rowCount = ps.executeUpdate();