我在 R 中有一个简单的 Shiny 应用程序,用于从用户那里读取 PDF 文件并显示它。我似乎无法让它工作。在 www 目录中的 Shiny 服务器上,我看到一个名为“myreport.pdf”的 1 KB 文件,它只有第一个字符
library(shiny)
ui <- shinyUI(fluidPage(
titlePanel("Testing File upload"),
sidebarLayout(
sidebarPanel(
fileInput('file_input', 'upload file ( . pdf format only)', accept = c('.pdf'))
),
mainPanel(
uiOutput("pdfview")
)
)
))
server <- shinyServer(function(input, output) {
observe({
req(input$file_input)
test_file <- readBin(input$file_input$datapath, what="character")
writeBin(test_file, "www/myreport.pdf")
})
output$pdfview <- renderUI({
tags$iframe(style="height:600px; width:100%", src="myreport.pdf")
})
})
shinyApp(ui = ui, server = server)
最佳答案
我认为问题在于二进制读写。相反,尝试使用 file.copy
复制文件似乎可行。此外,我还采用了 observeEvent
内的 iframe
以便 iframe 每次在同一 session 中上传 pdf 时都会更新。
更新代码:
library(shiny)
ui <- shinyUI(fluidPage(
titlePanel("Testing File upload"),
sidebarLayout(
sidebarPanel(
fileInput('file_input', 'upload file ( . pdf format only)', accept = c('.pdf'))
),
mainPanel(
uiOutput("pdfview")
)
)
))
server <- shinyServer(function(input, output) {
observe({
req(input$file_input)
#test_file <- readBin(input$file_input$datapath, what="raw")
#writeBin(test_file, "myreport.pdf")
#cat(input$file_input$datapath)
file.copy(input$file_input$datapath,"www", overwrite = T)
output$pdfview <- renderUI({
tags$iframe(style="height:600px; width:100%", src="0.pdf")
})
})
})
shinyApp(ui = ui, server = server)
关于r - 在 R Shiny 中上传和查看 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47395465/