请用java代码展示一段从前端获取视频或者图片并将其路径存储在数据库的代码
时间: 2024-02-03 18:15:07 浏览: 68
以下是一个简单的Java代码示例,演示如何从前端接收视频或图像文件,并将其路径存储在数据库中:
```java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 数据库连接信息
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String DB_USERNAME = "root";
private static final String DB_PASSWORD = "password";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取上传的文件
Part filePart = request.getPart("file");
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
// 保存上传文件到服务器
Path uploadPath = Paths.get(getServletContext().getRealPath("/uploads"));
Path filePath = Files.createTempFile(uploadPath, "", fileName);
try (var inputStream = filePart.getInputStream()) {
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
}
// 将文件路径存储到数据库
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO files (name, path) VALUES (?, ?)")) {
stmt.setString(1, fileName);
stmt.setString(2, filePath.toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw new ServletException("Unable to save file to database.", e);
}
response.sendRedirect(request.getContextPath() + "/success.jsp");
}
}
```
在这个示例中,我们使用了Servlet 3.0规范中的@MultipartConfig注解来支持文件上传。从HTTP请求中获取文件部分,然后将其保存到服务器上的一个临时文件中。然后,我们将文件路径存储在数据库中,以便以后可以检索它。
阅读全文