You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny R中实现PDF文件上传、显示与删除功能

Shiny R PDF上传、显示及删除功能实现方案

问题说明

开发Shiny R的PDF上传显示模块时,运行示例代码后出现*「Not Found」*错误,无法正常完成PDF上传展示效果。

问题解决方法

  • 需在Shiny项目根目录手动创建www文件夹:该目录是Shiny默认的静态资源托管目录,上传后的PDF需要存放在该目录下才能被前端正常加载,缺少目录会直接导致路径NotFound错误
  • 程序必须在浏览器中打开运行:RStudio内置的预览窗口对iframe加载PDF的支持存在异常,会导致即使路径正确也无法正常展示PDF

可正常运行的PDF上传展示代码

library(shiny)

ui <- shinyUI(fluidPage(
  
  titlePanel("Testing File upload"),
  
  sidebarLayout(
    sidebarPanel(
      fileInput('file_input', 'upload file ( . pdf format only)', accept = c('.pdf')),
      fileInput('file_input2', 'upload file2 ( . pdf format only)', accept = c('.pdf'))
    ),
    
    mainPanel(
      uiOutput("pdfview"),
      uiOutput("pdfview2")
    )
  )
))

server <- shinyServer(function(input, output) {
  
  observe({
    req(input$file_input)
    
    file.copy(input$file_input$datapath,"www\\pdf1", overwrite = T)
    
    output$pdfview <- renderUI({
      tags$iframe(style="height:600px; width:100%", src="pdf1\\0.pdf")
    })
    
  })
  
  observe({
    req(input$file_input2)
    
    file.copy(input$file_input2$datapath,"www\\pdf2", overwrite = T)
    
    output$pdfview2 <- renderUI({
      tags$iframe(style="height:600px; width:100%", src="pdf2\\0.pdf")
    })
    
  })
  
})

shinyApp(ui = ui, server = server)

删除功能实现思路

要实现PDF删除功能,补充以下逻辑即可:

  1. 在UI侧新增对应PDF的删除触发按钮,比如actionButton("del_pdf1", "删除第一个PDF")、actionButton("del_pdf2", "删除第二个PDF")
  2. 服务端编写按钮点击监听事件,触发后依次执行两个操作:
    • 调用file.remove()方法删除www目录下对应存储的PDF文件
    • 将对应PDF的UI输出赋值为NULL,清空页面上的PDF展示区域

内容的提问来源于stack exchange,提问作者Reza AM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:48:01