sqlserver+jsp+java bean上传文字和图片
时间: 2023-12-30 11:03:00 浏览: 139
要实现在 JSP 页面中上传文字和图片,需要涉及到以下几个步骤:
1. 编写 JSP 页面,设置表单,包含文字和图片上传控件。
2. 在 JSP 页面中,使用 JavaBean 技术获取表单提交的数据,包括文字和图片。
3. 将获取到的数据插入到 SQL Server 数据库中,包括文字和图片。
下面是一个简单的实现示例:
1. 编写 JSP 页面
```jsp
<form action="upload.jsp" method="post" enctype="multipart/form-data">
<label for="title">标题:</label>
<input type="text" id="title" name="title"><br>
<label for="content">内容:</label>
<textarea id="content" name="content"></textarea><br>
<label for="image">图片:</label>
<input type="file" id="image" name="image"><br>
<input type="submit" value="提交">
</form>
```
2. 编写 JavaBean
```java
public class UploadBean {
private String title;
private String content;
private String imagePath;
public UploadBean(HttpServletRequest request) throws IOException, ServletException {
title = request.getParameter("title");
content = request.getParameter("content");
Part imagePart = request.getPart("image");
if (imagePart != null) {
String imageName = getSubmittedFileName(imagePart);
imagePath = "/uploads/" + imageName;
String realPath = request.getServletContext().getRealPath("/uploads");
File imageFile = new File(realPath, imageName);
try (InputStream is = imagePart.getInputStream(); OutputStream os = new FileOutputStream(imageFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
}
}
}
public void saveToDatabase() throws SQLException, ClassNotFoundException {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase";
String username = "myuser";
String password = "mypassword";
try (Connection conn = DriverManager.getConnection(url, username, password)) {
String sql = "INSERT INTO mytable (title, content, image_path) VALUES (?, ?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, title);
stmt.setString(2, content);
stmt.setString(3, imagePath);
stmt.executeUpdate();
}
}
}
private String getSubmittedFileName(Part part) {
String header = part.getHeader("content-disposition");
if (header == null) {
return null;
}
for (String token : header.split(";")) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
}
```
3. 编写 JSP 页面处理上传操作
```jsp
<%@ page import="java.io.*, java.sql.*" %>
<%@ page import="javax.servlet.http.*, javax.servlet.*" %>
<%
try {
UploadBean uploadBean = new UploadBean(request);
uploadBean.saveToDatabase();
out.println("上传成功!");
} catch (Exception e) {
out.println("上传失败:" + e.getMessage());
}
%>
```
在这个示例中,我们使用 JavaBean 技术获取表单提交的数据,并将图片保存到服务器上的指定目录中。然后,我们使用 SQL Server JDBC 驱动程序将数据插入到数据库中。最后,在 JSP 页面中展示上传结果。
阅读全文