如何使用 R 编程在 Sqlite 中存储 .pdf 文件

How to store .pdf file in Sqlite using R programming

我正在 R-Shiny 上创建一个应用程序,我正在从用户那里获取我存储在 backed.But 中的 SQLite 数据库中的输入我关心的是我的表单我有一个基本上接受文件的上传文件输入喜欢 (.PDF,.jpeg,.png)(下面的屏幕截图)。

如果用户使用它上传任何文件,我希望将该文件存储在我的 SQLite 数据库中 table 以便进一步 use.But 我不知道如何使用 r 编程实现这一点。

如有任何帮助,我们将不胜感激。

您可以将对象(任何非表格形式的 R 输出,例如模型的输出)存储为 SQLite 中的 BLOB,在 R 中为此使用 serialize/unserialize,但在您需要之前使用 readBin 阅读原始 PDF,这里有一个例子:

path <- file.path(Sys.getenv("R_DOC_DIR"), "NEWS.pdf")

# see the PDF
browseURL(path)

# Read raw PDF
pdf <- readBin(con = path, what = raw(), n = file.info(path)$size)


library(RSQLite)

# Connect to DB
con <- dbConnect(RSQLite::SQLite(), ":memory:")

# Serialize raw pdf
pdf_serialized <- serialize(pdf, NULL)
# Create a data.frame
df <- data.frame(pdfs = I(list(pdf_serialized)))

# Write the table in database
dbWriteTable(conn = con, name = "mytable", value = df, overwrite = TRUE)


# Read your table
out <- dbReadTable(conn = con, name = "mytable")

# unserialize
pdf_out <- unserialize(out$pdfs[[1]])

# Write the PDF in a temporary file
tmp <- tempfile(fileext = ".pdf")
writeBin(object = pdf_out, con = tmp)

# open it
browseURL(tmp)

类似于 Victorp 的回答,您也可以对数据进行 base64 编码并将其作为文本存储在数据库中:

file <- "mypdf.pdf"
con <- dbConnect(...)
table <- "mypdf_table"

bin <- readBin(file, raw(), n = file.size(file))
enc_data <- base64enc::base64encode(bin)
  
dd <- data.frame(
  file = file,
  data = enc_data 
)
  
DBI::dbWriteTable(con, table, dd, append = TRUE)