R Shiny上传图片生成可下载PDF报告时图片显示为数据问题求助
问题原因及修改方案
核心错误点
- 传参错误:你传递给Rmd的
params$image是完整的input$file1对象(包含文件路径、文件名、大小等信息的列表),而非图片的本地存储路径,直接打印该对象自然会输出结构化数据而非图片。 - Rmd渲染逻辑错误:Rmd中插入图片不能直接打印路径,需要调用
knitr::include_graphics()函数加载路径完成图片渲染。 - 额外可优化点:
renderImage默认会在渲染后删除临时文件,需添加deleteFile = FALSE避免图片被提前清理- 你的UI中未定义
slider输入控件,input$slider会返回NULL,无用参数可直接删除 - 建议加
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
相关产品推荐
相关产品推荐

