【问题标题】:Display all images from Database (blob) on a jsp file in a table在表中的 jsp 文件上显示来自数据库 (blob) 的所有图像
【发布时间】:2016-12-18 12:08:58
【问题描述】:

我需要你的帮助。我想在 jsp 文件中显示我的数据库中的所有图像(那里有 6 个图像)。为什么使用 JSP 文件而不使用 outputreader? -> 因为我想在下一步中用 css 设置表格的样式,所以我必须以这种特殊的方式来做这件事。

选择数据库的所有图片:

public static List<Picture> displayPicture() {

List<Picture> list = new ArrayList<Picture>();

try {

    Class.forName("com.mysql.jdbc.Driver");

    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:9999/xxx", "xxx", "xxx");

    String sql = "SELECT * FROM PICTURES";

    PreparedStatement ps = conn.prepareStatement(sql);

    ResultSet rs = ps.executeQuery();

    while (rs.next()) {

         byte[] imageData = rs.getBytes("File_Data");
         String imageFileName = rs.getString("File_Name");

         Picture picture = new Picture();
         picture.setImageData(imageData);
         picture.setImageFileName(imageFileName);
         list.add(picture);
    }

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

现在我想将此列表保存在 setAttribute 中以将其发送到 JSP 文件:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Picture> list =null;
list = DBUtils.displayPicture();

request.setAttribute("pictureList", list);

RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/pictureView.jsp");
dispatcher.forward(request, response);

最后是 JSP 文件:

<table>
<c:forEach items="${pictureList}" var="picture">
    <tr>
        <td>${picture.imageData}</td>
    </tr>
</c:forEach>

所以我想在表格中显示所有图像。目前,桌子看起来如何并不重要。使用此代码,我只能得到一个带有特殊数字和字母的表格。我认为它是二进制代码,对吧? (例如:beans.Picture@22debaab 或 [B@3f391312])

现在哪里出错了?在 JSP 文件的代码中,因为我必须使用

<img src=""> 

还是别的什么?如果这是错误,应该如何编码?

谢谢大家

亲爱的新手

【问题讨论】:

  • 你能把你的图片数据转换成base64格式吗?
  • @AtaurRahmanMunna 我已经尝试过使用 base64 但我没有工作。如果你用 base64 来解决,你会怎么解决?
  • @JoseLuis 看起来真的很棒!谢谢你我试试
  • @newbieQwer 请显示代码,你用base64尝试了什么?

标签: java css mysql jsp


【解决方案1】:

在控制器端使用代码sn-p。

List<String> list = new ArrayList<String>();
while (rs.next()) { 
    byte[] imageData = rs.getBytes("File_Data"); 
    list.add(org.apache.commons.codec.binary.Base64.encodeBase64String(imageData)); 
}
request.setAttribute("pictureList", list);

并像这样在html页面中显示,

<table>
    <c:forEach items="${pictureList}" var="picture">
        <tr>
            <td><img src="data:image/jpg;base64,${picture}"/></td>
        </tr>
    </c:forEach>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多