将 pptx 文件转换为二进制存储在 db 中,然后在检索后转换回 pptx

Convert pptx file to binary to store in db and then convert back to pptx after retrieval

我看到了这个post:

https://community.rstudio.com/t/storing-and-retrieving-files-images-in-a-database-from-shiny-app/28122

并想了解如何在将二进制文件转换回二进制文件之前将其转换回普通文件类型。在 post 中提到了这些步骤:

如何序列化回一个文件,在本例中是一个 pptx 文件,该文件存储在 shinyR 应用程序将与之交互的 sql 数据库中。感谢您的时间和指导。谢谢

# open pptx as binary and write as binary to new location
rtn_filename <- "/path/to/pptx-file"
read_ppt <- readBin(rtn_filename, what= raw(), n=file.info(rtn_filename)$size)
con = file(file.path(dirname(rtn_filename), "ppt_binary.dat"), "wb")
writeBin(object = read_ppt, con = con)
close(con)

# read the binary file
filepath <- file.path(dirname(rtn_filename), "ppt_binary.dat")
binary_file <- readBin(filepath, what = raw(), n=file.info(filepath))

    
sql_smt <- "UPDATE PPTFILES SET PPT_FILE =  where experiment_id = 'FY21w1p214';" 

# upload to sql db
rs  <- dbExecute(
  con, 
  statement=sql_smt, 
  list(paste0("\x", paste(binary_file, collapse = "")))
)

# check that the original file and what is in the db is the same
get_res <- dbGetQuery(con, "SELECT PPT_FILE from PPTFILES WHERE experiment_id = 'FY21w1p214'")
identical(get_res$ppt_file[[1]], binary_file) #TRUE

我在 Postgresql 数据库上完成了文件 uploading/downloading。

在此数据库中,我用于字段类型的选项是文本。

如果您正在使用 SQL 服务器,nvarchar(max) 可能最适合此方法。

此方法背后的想法是以 base64 对文件进行编码并将其作为文本插入数据库中。由于编码,数据大小将大于原始文件。无论您拥有什么类型的文件内容或格式,powerpoint 或其他格式都没有关系。你最好直接在 R 中进行编码。

如果在 postgresql 中执行,以下代码将有效。如果使用另一个 dbms,请进行调整,或者它可以保持不变我还没有检查,因为我手头没有 SQL 服务器:

在数据库中

CREATE TABLE files_table
(
    file_name TEXT NOT NULL,
    file_content TEXT NOT NULL
)

在 R 中,将文件保存到 DB

library(base64enc)
library(DBI)
pg = dbDriver("PostgreSQL")
file_name <- "/tmp/some_file.pptx"
file_content <- base64encode(file_name)
con = dbConnect(pg, user="user", password="password",
              host="hostname", port=5432, dbname="dbname")
qry <- sprintf("INSERT INTO files_table ( file_name, file_content ) values( '%s', '%s')",file_name, file_content)
dbExecute(con,qry)

从数据库中按文件名加载文件,并以与加载时相同的名称将其写入磁盘

## same code from before to connect to database here and same libraries
file_name <- "/tmp/some_file.pptx"
qry <- sprintf("SELECT file_content FROM files_table WHERE file_name='%s' LIMIT 1",file_name)
data <- dbGetQuery(con, qry)
raw_data <- base64decode(data[1,]$file_content)
write.filename = file(file_name, "wb")
writeBin(raw_data,write.filename)
close(write.filename)

当然,它不能很好地处理重复的文件名,这取决于它可能重要与否的用例。