如何动态添加图片到Rmd Shiny文档中?

问题描述 投票:0回答:1

我基于 R Markdown 文档创建了一个 Shiny 应用程序。在其他输入中,用户可以选择“类型”。类型 -

choices
selectInput
源自位于 Shiny 应用程序的“www”文件夹中的所有图像文件的名称(特别是“www”中名为“motives”的子文件夹)。当用户选择类型时,会显示相应的图像文件(当然其他东西也由类型控制)。

此设置背后的基本原理是应用程序的用户可以轻松添加或删除类型/动机。他们只需将一个专门命名的图像文件放入 SharePoint 文件夹中,然后将其与应用程序的“www/motives”文件夹同步。这样他们就不需要填写路径列表或联系管理员(我自己)来修改类型/动机集。

当前的问题是,仅当浏览器先前解析了图像路径时,图像才会出现(抱歉,我不知道如何更好地描述它)。如果我添加包含 HTML 标签的 HTML 注释(只是注释!)来显示图像,它就可以工作。但是,由于用户可能在动机文件夹中添加或删除图像,因此我无法对这些

img
标签进行硬编码。如果没有注释(示例中的 type-b),我会收到以下错误:

无法加载资源:服务器响应状态为 404(未找到)

我还能做什么?

这是保存为“app.Rmd”的示例应用程序的代码:

---
pagetitle: "Test"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
```

```{r, include=FALSE}
# create image files just for this example app
png(filename = "www/motives/default.png", width = 200, height = 200)
plot(1:5, 1:5, type = "p", col = "grey", pch = 16, xaxt = "n", yaxt = "n", xlab = NA, ylab = NA)
dev.off()
png(filename = "www/motives/type-a.png", width = 200, height = 200)
plot(1:5, 1:5, type = "p", col = "blue", pch = 16, xaxt = "n", yaxt = "n", xlab = NA, ylab = NA)
dev.off()
png(filename = "www/motives/type-b.png", width = 200, height = 200)
plot(1:5, 1:5, type = "p", col = "red", pch = 16, xaxt = "n", yaxt = "n", xlab = NA, ylab = NA)
dev.off()
```

```{r, echo=FALSE}
# 
selectInput("type", label = "Type", choices = "default")
```

```{r, include=FALSE}
# get motives from all files in the motives-folder
motives <- data.frame(path = list.files("www/motives")) %>%
  mutate(title = gsub(".png", "", .$path))

updateSelectInput(inputId = "type",
                  choices = motives$title)

# create title output
title <- reactive({
  if(input$type != "default") {
    paste0("Special type '", input$type, "'")
  } else {
    "Default type"
  }
})

# create motive output
motive <- reactive({
  HTML(paste0('<img src="app_files/www/motives/', input$type, '.png" />'))
})
```

<h4>`r renderText({title()})`</h4>
<div id="motive">`r renderUI({motive()})`</div>

<!--- 
if this part is missing,
the motives are gone

<img src="www/motives/default.png" />
<img src="www/motives/type-a.png" />

the img tag for type-b is left out,
thus the corresponding image is not displayed 
--->

显示默认动机和类型-a 动机,类型-b 不显示:

html r shiny
1个回答
0
投票

您似乎在图像的 HTML 路径中使用“app_files”。您需要在文档本身中进行设置。我不相信当你运行一个闪亮的文档时,它会自动共享你的

www
文件夹。所以你可以明确地设置它

shiny::addResourcePath("app_files", "www/motives")

您可以将其添加到您的设置块中。然后当你要使用图像时,使用

motive <- reactive({
  HTML(paste0('<img src="app_files/', input$type, '.png" />'))
})
© www.soinside.com 2019 - 2024. All rights reserved.