指定要从R Shiny应用程序下载的目标文件夹



我正在开发一个Shiny应用程序,用户在其中上传一个文件,然后对其进行处理以生成报告,用户可以将其下载为可编辑的Word.doc.

它按预期工作,除此之外,尽管;另存为";对话框窗口出现,似乎允许您选择目标目录,生成的.doc文件最终被保存到一个随机生成名称的临时目录中(这是在Windows下(。

我怀疑这是由于使用了tempdir命令,它是使用rmarkdown生成下载文件的一部分。

应如何修改以下代码以允许选择目标文件夹?

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#
library(shiny)
library(knitr)
# Define UI for application that draws a histogram
ui <- fluidPage(
uiOutput('markdown'),
# Application title
titlePanel("Apptitle"),
# Sidebar with file input
sidebarLayout(
sidebarPanel(
fileInput(
inputId = "file1",
label = "Select file(s)",
multiple = TRUE,
accept = NULL,
width = NULL,
buttonLabel = "Browse...",
placeholder = "No file(s) selected"
),
downloadButton("report", "Generate report")
),
)
)
server <- function(input, output) {

output$report <- downloadHandler(
reactive(file <- input$file1),
filename = "wordreport.doc",
content = function(file) {
tempReport <- file.path(tempdir(), "wordreport.Rmd")
file.copy("wordreport.Rmd", tempReport, overwrite = TRUE)
params <- list(report.data = input$file1)
rmarkdown::render(tempReport, output_file = "wordreport.doc",
params = params,
envir = new.env(parent = globalenv()))
})
}
shinyApp(ui = ui, server = server)

谢谢你的帮助!

编辑:修复,使用下面的解决方案,以及这里建议的代码编辑:将数据帧作为参数从Shiny应用程序传递到RMarkdown

reactive(file <- input$file1)作为contentType参数传递给downloadHandler(),这不太好。此外,您没有向作为content函数参数给定的file写入任何内容。

删除reactive(file <- input$file1)行,并在rmarkdown::render()中指定output_file = file,下载就可以了。

正如评论中所讨论的,你将无法控制下载路径——这将由用户的网络浏览器及其设置决定。

这里有一个更简单的应用程序,可以下载正常运行的文件,供参考:

library(shiny)
ui <- fluidPage(
sliderInput("value", "Some value", 1, 5, 2),
downloadButton("report", "Generate report")
)
server <- function(input, output) {
output$report <- downloadHandler(
filename = "wordreport.doc",
content = function(file) {
params <- list(value = input$value)
rmarkdown::render(
system.file("examples/knitr-minimal.Rmd", package = "knitr"),
output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
shinyApp(ui, server)

相关内容

最新更新