我有一个闪亮的应用程序,在这个应用程序中,有一个表格概述了一些项目。我希望用户可以通过单击按钮来下载这些项目。
我当前的方法在某种程度上有效,但如果我修改看似不相关的部分,则会导致非常奇怪的行为。
这是我的最小示例的解释:
我有一个包含两个 data.frames 的列表,我想为其提供下载选项。为了实现这一目标,我制作了操作按钮,使用 onclick 事件将所需的 data.frame 写入输入。当此文本输入更改时,它会触发一个闪亮的下载按钮来下载所需的 data.frame。
这种方法看起来相当复杂,但通常效果很好。看来下载按钮让事情变得复杂了。
library(shiny)
library(shinyjs)
ui <- fluidPage(
DT::dataTableOutput("dt"),
shinyjs::useShinyjs(),
div( # replace 'div' by 'hidden' and see what happens
"should not be visible to user",
textInput(inputId = "datasetToDownload", label = "Dataset to Download"),
downloadButton(outputId = "downloadButton")
)
)
datasetsToDownload <- c("iris", "mtcars")
server <- function(input, output, session) {
output$dt <- DT::renderDT({
df <- data.frame(
"datasets" = datasetsToDownload,
"download" = sapply(datasetsToDownload, function(id) {
as.character(actionButton(
inputId = paste0("download", id),
label = paste("download", id),
onclick = sprintf("Shiny.setInputValue('datasetToDownload', '%s', {priority: 'event'})", id)
))
})
)
DT::datatable(
df,
escape = setdiff(names(df), c("download"))
)
})
observeEvent(input$datasetToDownload,{
if (input$datasetToDownload %in% datasetsToDownload){
shinyjs::click("downloadButton")
}
})
output$downloadButton <- downloadHandler(
filename = function() {
# Use the selected dataset as the suggested file name
filename <- paste0(input$datasetToDownload, ".csv")
print("filename:")
print(filename)
filename
},
content = function(file) {
print("content")
print("file:")
print(file)
# Write the dataset to the `file` that will be downloaded
write.csv(get(input$datasetToDownload), file)
}
)
}
shinyApp(ui, server, options = list(launch.browser = TRUE))
这工作正常,但是当我隐藏
textInput
和 downloadButton
时,它会下载一个 49aqnopL.htm
,它接近但不完全等于闪亮应用程序的 html 代码。 downloadHandler
内的打印语句也不会发生。我觉得这种行为非常令人惊讶。你知道为什么会出现这种情况吗?
另外:您对我如何实现我的目标有什么建议吗?
这基本上是 R Shiny - 如何拥有自动下载 csv 文件的操作按钮(不是下载按钮?)
因此,切换到
conditionalPanel("false")
而不是 hidden()
可以解决问题:
conditionalPanel(
"false",
"should not be visible to user",
textInput(inputId = "datasetToDownload", label = "Dataset to Download"),
downloadButton(outputId = "downloadButton")
)