Javaweb新闻管理界面上传文字图片代码
时间: 2023-08-06 10:03:01 浏览: 51
以下是一个简单的Java Web新闻管理界面上传文字和图片的代码示例:
1. 在JSP页面上添加一个表单,用于输入新闻标题、内容和上传图片:
```
<form action="AddNewsServlet" method="post" enctype="multipart/form-data">
<label for="title">标题:</label>
<input type="text" id="title" name="title" required>
<br>
<label for="content">内容:</label>
<textarea id="content" name="content" rows="5" required></textarea>
<br>
<label for="image">图片:</label>
<input type="file" id="image" name="image">
<br>
<input type="submit" value="提交">
</form>
```
2. 在Servlet中处理表单提交,包括读取新闻标题和内容,上传图片到服务器,并保存新闻和图片的路径到数据库:
```
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 读取新闻标题和内容
String title = request.getParameter("title");
String content = request.getParameter("content");
// 上传图片到服务器
Part filePart = request.getPart("image");
String fileName = filePart.getSubmittedFileName();
InputStream fileContent = filePart.getInputStream();
String filePath = "/path/to/images/" + fileName;
Files.copy(fileContent, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
// 保存新闻和图片的路径到数据库
String sql = "INSERT INTO news (title, content, image) VALUES (?, ?, ?)";
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/news", "username", "password");
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, title);
stmt.setString(2, content);
stmt.setString(3, filePath);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
// 重定向到新闻列表页面
response.sendRedirect("news.jsp");
}
```
注意,上传图片需要确保文件名唯一,并且需要对文件的大小、类型进行合法性检查。保存新闻和图片路径到数据库时,需要根据实际情况修改SQL语句和数据库连接信息。