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

R Shiny上传图片生成可下载PDF报告时图片显示为数据问题求助

问题原因及修改方案

核心错误点

  • 传参错误:你传递给Rmd的params$image是完整的input$file1对象(包含文件路径、文件名、大小等信息的列表),而非图片的本地存储路径,直接打印该对象自然会输出结构化数据而非图片。
  • Rmd渲染逻辑错误:Rmd中插入图片不能直接打印路径,需要调用knitr::include_graphics()函数加载路径完成图片渲染。
  • 额外可优化点:
    1. renderImage默认会在渲染后删除临时文件,需添加deleteFile = FALSE避免图片被提前清理
    2. 你的UI中未定义slider输入控件,input$slider会返回NULL,无用参数可直接删除
    3. 建议加req(input$file1)避免未上传图片时触发报错

修改后的代码

app.R

library(shiny)

ui <- fluidPage(
  titlePanel('Upload Image Test'),
  sidebarLayout(  
    sidebarPanel(
      fileInput(
        inputId = "file1",
        label = "Upload Image",
        accept = c('image/png', 'image/jpeg','image/jpg')
      ),
      tags$hr()),
    mainPanel(
      textOutput("filename"),
      imageOutput(outputId = "uploaded_image"),
      downloadButton("report", "Generate report")
    )
  )
)

server <- function(input, output) {
  # 图片渲染逻辑修复
  output$uploaded_image <- renderImage({
    req(input$file1) # 未上传图片时不执行后续逻辑
    list(
      src = input$file1$datapath,
      deleteFile = FALSE # 禁止自动删除临时图片文件
    )
  })
  
  output$report <- downloadHandler(
    filename = "report.pdf",
    content = function(file) {
      tempReport <- file.path(tempdir(), "report.Rmd")
      file.copy("report.Rmd", tempReport, overwrite = TRUE)
      # 传参改为直接传图片路径
      params <- list(image = input$file1$datapath)
      rmarkdown::render(tempReport, output_file = file,
                        params = params,
                        envir = new.env(parent = globalenv())
      )
    }
  )
}
shinyApp(ui, server)

report.Rmd

---
title: "report"
author: "Author"
date: "4/14/2019"
output: pdf_document
params:
  image: "Null"
---
knitr::include_graphics(params$image)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:36:04