JSP将图片储存入数据库
时间: 2023-09-10 08:11:30 浏览: 83
好的,以下是JSP将图片存储到数据库的基本步骤:
- 创建数据库表,包含一个用于存储图片二进制数据的BLOB类型字段,例如:
CREATE TABLE images (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(50) NOT NULL,
image BLOB NOT NULL
);
- 在JSP页面中编写上传图片的表单,例如:
<form action="upload.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="上传">
</form>
- 在upload.jsp页面中,处理上传的图片文件,将其转换成二进制数据,再将数据保存到数据库中,例如:
<%@ page import="java.io.*, java.sql.*" %>
<%
// 获取上传的文件
Part filePart = request.getPart("image");
InputStream inputStream = filePart.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// 将文件转换成二进制数据
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
// 将二进制数据保存到数据库中
String title = "图片标题";
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
pstmt = conn.prepareStatement("INSERT INTO images (title, image) VALUES (?, ?)");
pstmt.setString(1, title);
pstmt.setBytes(2, imageBytes);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
这样,上传的图片就会被存储到数据库中。当需要显示图片时,可以从数据库中读取二进制数据并转换成图片格式,再将其显示在页面上。
相关推荐















