把mysql读取的图片显示在jsp 页面上

先创建数据库

如:

create table bcctphoto(
    photoid int primary key auto_increment,
    photoname    varchar(50)    NOT NULL,
    photo    blob
);


<2>把show.jsp放在tomcat的任意目录下. show.jsp作用:从数据库中读出blob,并产生image/jpg.

show.jsp文件如下:

<%@ page contentType="text/html; charset=gbk" %>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*, javax.sql.*" %>
<%@ page import="java.util.*"%>
<%@ page import="java.math.*"%>

<%
String photo_no = request.getParameter("photo_no");

//mysql连接
Class.forName("com.mysql.jdbc.Driver").newInstance();
String URL="jdbc:mysql://localhost:3306/bigdate?user=root&password=mysqladmin";
Connection con = DriverManager.getConnection(URL);

//oracle连接
//String URL="jdbc:oracle:thin@localhost:1521:orcl2";
//user="system";
//password="manager";
//Connection con = DriverManager.getConnection(URL,user,password);


try{
// 准备语句执行对象
Statement stmt = con.createStatement();

String sql = " SELECT * FROM PHOTO WHERE photo_no = "+ photo_no;
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
Blob b = rs.getBlob("photo_image");
long size = b.length();
//out.print(size);
byte[] bs = b.getBytes(1, (int)size);
response.setContentType("image/jpeg");
OutputStream outs = response.getOutputStream();
outs.write(bs);
outs.flush();
rs.close();
}
else {
rs.close();
response.sendRedirect("./images/error.gif");
}
}
finally{
con.close();
}
%>

<3>把如下文件放在show.jsp的同一目录下.

index.html文件如下:

<HTML>
<HEAD>
<TITLE> 图像测试 </TITLE>

</HEAD>

<BODY>
<TABLE>
<TR>
<TD>图像测试</TD>
</TR>
<TR>
<TD><img src="show.jsp?photo_no=2"></TD>
</TR>
</TABLE>

</BODY>
</HTML>



异常处理: 如果出现 getOutputStream() has already been called for this response


异常解析:这里是在释放在jsp中使用的对象,会调用response.getWriter(),因为这个方法是和response.getOutputStream()相冲突的!所以会出现以上这个异常。然后当然是要提出解决的办法,其实挺简单的,在使用完输出流以后调用以下两行代码即可:


解决方法:添加代码

  1. out.clear();  
  2. out = pageContext.pushBody(); 

如下代码:

  • //注意看以下几句的使用  
  • outs.flush();  
  • outs.close();  
  • outs=null;  
  • response.flushBuffer();  
  • out.clear();  
  • out = pageContext.pushBody(); 


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,我们需要在前端页面中添加一个文件上传的表单,如下所示: ``` <form action="upload.jsp" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="file"> <input type="submit" value="上传"> </form> ``` 其中,`action` 属性指定了表单提交的地址为 `upload.jsp`,`enctype` 属性指定了表单数据的编码方式为 `multipart/form-data`,这样才能支持文件上传。 接下来,我们需要编写 `upload.jsp` 页面来实现图片的上传和保存到数据库中。代码如下: ``` <%@ page import="java.io.*,java.sql.*" %> <% String savePath = "D:\\upload\\"; // 上传文件的保存路径 File file = new File(savePath); if (!file.exists() && !file.isDirectory()) { System.out.println(savePath + "目录不存在,需要创建"); file.mkdir(); } String fileName = ""; // 上传的文件名 String contentType = request.getContentType(); if (contentType != null && contentType.toLowerCase().startsWith("multipart/")) { DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; while (totalBytesRead < formDataLength) { byteRead = in.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead += byteRead; } String fileData = new String(dataBytes); fileName = fileData.substring(fileData.indexOf("filename=\"") + 10); fileName = fileName.substring(0, fileName.indexOf("\n")); fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1, contentType.length()); int pos; pos = fileData.indexOf("filename=\""); pos = fileData.indexOf("\n", pos) + 1; pos = fileData.indexOf("\n", pos) + 1; pos = fileData.indexOf("\n", pos) + 1; int boundaryLocation = fileData.indexOf(boundary, pos) - 4; int startPos = ((fileData.substring(0, pos)).getBytes()).length; int endPos = ((fileData.substring(0, boundaryLocation)).getBytes()).length; FileOutputStream fileOut = new FileOutputStream(savePath + fileName); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); } String imageUrl = "http://localhost:8080/myapp/upload/" + fileName; // 图片的 URL 地址 Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mydb"; String username = "root"; String password = "root"; Connection conn = DriverManager.getConnection(url, username, password); PreparedStatement pstmt = conn.prepareStatement("INSERT INTO images (image_url) VALUES (?)"); pstmt.setString(1, imageUrl); pstmt.executeUpdate(); pstmt.close(); conn.close(); response.sendRedirect("index.jsp"); %> ``` 代码解释: 1. 首先,我们指定了上传文件的保存路径为 `D:\upload\`,并检查这个路径是否存在,如果不存在则创建。 2. 接着,我们获取上传文件的文件名,并使用 `DataInputStream` 读取文件的二进制数据,最终将文件保存到 `D:\upload\` 目录下。 3. 我们使用 `imageUrl` 变量存储图片的 URL 地址,其中 `http://localhost:8080/myapp` 是 Web 应用的根路径,`upload` 是图片存储的子目录,`fileName` 是上传的图片文件名。 4. 接着,我们使用 JDBC 连接 MySQL 数据库,并将图片的 URL 地址插入到 `images` 表中。 5. 最后,我们使用 `response.sendRedirect("index.jsp")` 将用户重定向到首页。 最后,我们在前端页面中通过以下代码来获取图片显示: ``` <% Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mydb"; String username = "root"; String password = "root"; Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM images"); while (rs.next()) { String imageUrl = rs.getString("image_url"); %> <img src="<%=imageUrl%>"> <% } rs.close(); stmt.close(); conn.close(); %> ``` 代码解释: 1. 首先,我们使用 JDBC 连接 MySQL 数据库,并查询 `images` 表中的所有数据。 2. 接着,我们通过 `while` 循环遍历查询结果,并使用 `imageUrl` 变量获取每一行数据中的图片 URL 地址。 3. 最后,我们通过 `<img>` 标签将图片显示页面上。 注意:为了安全起见,我们应该对上传的文件进行严格的类型检查和大小限制,以避免上传恶意文件和占用过多的服务器资源。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值