gpt4 book ai didi

java - 如何制作一个下载按钮来检索sql数据库中的pdf文件?(java swing)

转载 作者:行者123 更新时间:2023-12-01 18:00:43 25 4
gpt4 key购买 nike

大家好!我正在尝试使用 java swing 创建一个桌面应用程序,其中用户可以将 pdf 文件上传到 mysql 数据库。我已经在应用程序中完成了上传部分,但在应用程序中制作下载按钮时遇到了问题。 download按钮的功能是检索mysql数据库中的pdf文件,然后下载到用户电脑中。

这是我在从 https://www.java-tips.org/other-api-tips-100035/69-jdbc/845-how-to-storeretrieve-pdf-document-tofrom-sqlserver.html 插入 pdf 文件时发现的内容上面的链接已经有获取pdf数据的功能,但我似乎不明白如何在我的下载按钮中实现它。

  public void upload(Connection conn,String filename) {
int len;
String query;
PreparedStatement pstmt;

try {
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
len = (int)file.length();
query = ("insert into fileStorage VALUES(?,?,?)");
pstmt = conn.prepareStatement(query);
pstmt.setString(1,file.getName());
pstmt.setInt(2, len);

//method to insert a stream of bytes
pstmt.setBinaryStream(3, fis, len);
pstmt.executeUpdate();

} catch (Exception e) {
e.printStackTrace();
}
}

我遇到的麻烦是为我的下载按钮创建一个功能。如何在单击下载按钮后从数据库检索文件并同时下载它。

最佳答案

是的,不幸的是我不知道你的表格式,但是我们应该能够创建一个准备好的语句来从数据库获取文件原始字节。以下将从数据库获取字节数组,然后根据需要从原始字节创建一个新文件。

  1. 将 fileName 更改为文件名列的正确名称。
  2. 将 fileContent 更改为字节数组的列名称。
  3. 确保 fileContent 是 varbinary 类型。
  4. 将 download(Connection, String) 引用中的 null 替换为合法的非 null Connection 引用。
    public static void main(String[] args) {
try {
byte[] download = download(null, "test");

Path output = Paths.get("my", "output", "file.pdf");

Files.write(output, download, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
} catch (IOException | SQLException e) {
throw new RuntimeException("Uh oh something went wrong!", e);
}
}

static byte[] download(Connection connection, String fileName) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM fileStore WHERE fileName = ?")) {
statement.setString(1, fileName);

try (ResultSet results = statement.getResultSet()) {
if (results.next()) {
return results.getBytes("fileContent");
}
}
}
throw new IllegalStateException("No file can be found for this name.");
}

关于java - 如何制作一个下载按钮来检索sql数据库中的pdf文件?(java swing),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60637065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com