jsp+MySQL代码实现图片的上传和获取显示
时间: 2024-01-03 12:05:17 浏览: 50
首先,我们需要在前端页面中添加一个文件上传的表单,如下所示:
```
<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>` 标签将图片显示在页面上。
注意:为了安全起见,我们应该对上传的文件进行严格的类型检查和大小限制,以避免上传恶意文件和占用过多的服务器资源。