jsp 上传图片 mysql_jsp如何上传照片到mysql,再查询在jsp中显示
时间: 2023-08-15 22:07:05 浏览: 46
可以按照以下步骤来实现图片上传到 MySQL 数据库中,并在 JSP 页面中显示:
1. 创建一个表用于存储图片的二进制数据:
```sql
CREATE TABLE `image` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`image` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
2. 在 JSP 页面中使用表单元素来上传图片:
```html
<form action="upload.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" value="上传" />
</form>
```
3. 在 upload.jsp 页面中获取上传的图片,并将其保存到数据库中:
```java
// 获取上传的文件
Part filePart = request.getPart("image");
InputStream inputStream = filePart.getInputStream();
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
// 将图片保存到数据库
String name = filePart.getSubmittedFileName();
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password");
stmt = conn.prepareStatement("INSERT INTO image(name, image) VALUES (?, ?)");
stmt.setString(1, name);
stmt.setBytes(2, bytes);
stmt.executeUpdate();
} finally {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
```
4. 在 JSP 页面中查询数据库中的图片,并将其显示出来:
```java
<%-- 查询数据库中的图片 --%>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM image");
while (rs.next()) {
String name = rs.getString("name");
byte[] bytes = rs.getBytes("image");
%>
<%-- 显示图片 --%>
<img src="data:image/jpeg;base64,<%=Base64.getEncoder().encodeToString(bytes)%>" />
<%
}
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
```
注意:上述代码只是示例代码,应该根据实际情况进行修改和优化。例如,可以对上传的图片进行类型和大小的验证,防止恶意上传和占用过多的存储空间。