【问题标题】:How to specify file and path to save a file with R-shiny and shinyFiles?如何指定文件和路径以使用 R-shiny 和 shinyFiles 保存文件?
【发布时间】:2017-01-23 20:08:43
【问题描述】:

我正在使用 R(闪亮)并希望将数据框保存为 excel 文件。 为此,我使用“shinyFiles”包,以便用户可以指定 excel 文件的存储位置:

服务器.R 图书馆(闪亮) 库(闪亮文件)

shinyServer(function(input, output, session) {

## ShinyFiles : get the user favorite directory
volumes=c(home = '~/'),
shinyDirChoose(input, 'dir', roots=volumes, filetypes = c('','xlsx')),
output$dir.res <- renderPrint({parseDirPath(volumes, input$dir)}),

## Button to save the file
observeEvent(input$button.save, {

## A standard file name
A <- "name"
B <- "family
if( input$text == "File name..." ) outFile <- paste( A, "_", B, ".xlsx", sep="" )

## Append the path to the file name
outFile <- paste( parseDirPath(volumes, input$path.out), outFile, sep="/" )

## The data to be saved
x=seq(from=0,to=10,by=1)
d = data.frame( x )
write.xlsx( d, outFile )
}

和 ui.R

library(shiny)
library(shinyFiles)

shinyUI(fluidPage(sidebarLayout(

## Choose the output directory
shinyDirButton("dir", "Choose directory", "Upload"),
## Choose the output file name
textInput("text", label = "", value = "File name..."),
## Save the data
actionButton("button.save", "Save the file"),
## Give the path selected
verbatimTextOutput("dir.res")
)))

尽管找到了所有类似问题的示例,但我已经尝试了 2 小时(耻辱..),并将感谢您的帮助

【问题讨论】:

  • 我觉得这里有误会。 shinyFiles 应该是 A shiny extension for server side file access,而不是用于选择客户端文件。要保存文件,只需使用普通的downloadButton 和关联的downloadHandler
  • 我是 R Shiny 的新手,所以可能会产生误解,但是我希望用户能够选择他要保存文件的位置,也就是说,如果我是正确的,与 downloadButton 的作用不同。
  • 文件下载通常由网络浏览器处理,而不是由 HTML 控制(存在安全问题,因为网页不应该看到您的本地硬盘驱动器)。如果您的用户使用的是 Firefox,他们可以这样做 pcworld.com/article/217112/missing_downloads.html 但通常这是特定于浏览器的
  • 我明白了,但是我的 R-shiny 脚本将在计算机上本地运行,而不是在服务器上。我正在寻找一种不依赖于浏览器的方式。
  • 如果您的代码要在计算机上运行,​​并且用户要在同一台计算机上选择下载位置,shinyFiles 应该可以工作。如果可能的话,我会尝试并给出答案。

标签: r excel save shiny


【解决方案1】:

这是一个工作示例。同样,这假设您在自己的计算机上运行应用程序,并且允许用户访问此计算机上的文件夹。您可以设置允许用户保存文件的根文件夹(参见UserFolder,用户将能够选择该根目录的任何子文件夹)

library(shiny)
library(shinyFiles)
library(xlsx)

ui <- shinyUI(fluidPage(

  titlePanel("Example"),
  shinySaveButton("save", "Save file", "Save file as ...", filetype=list(xlsx="xlsx"))

))

server <- shinyServer(function(input, output, session) {

  observe({
    volumes <- c("UserFolder"="D:/Data")
    shinyFileSave(input, "save", roots=volumes, session=session)
    fileinfo <- parseSavePath(volumes, input$save)
    data <- data.frame(a=c(1,2))
    if (nrow(fileinfo) > 0) {
      write.xlsx(data, as.character(fileinfo$datapath))
    }
  })
})

shinyApp(ui = ui, server = server)

【讨论】:

    猜你喜欢
    • 2015-09-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多