R Shiny:按下按钮上传文件

tej*_*ale 7 upload action r shiny

我知道网上已经有一些材料可以回答我的问题,但它们似乎都不适合我.我想那是因为我不太了解Shiny的反应式编程.

所以,我希望创建一个界面,让用户选择一个文件fileInput,只在点击上传按钮时上传.我尝试了各种论坛的一些解决方案,但都没有.以下是我最近的尝试:

#ui.R

library(shiny)

shinyUI(pageWithSidebar(


    headerPanel(""),

    sidebarPanel(

            fileInput("in_file", "Input file:",
                    accept=c("txt/csv", "text/comma-separated-values,text/plain", ".csv")),
            checkboxInput(inputId="is_header", label="Does the input file have column names?", value=TRUE),
            actionButton("upload_data", "Upload Data"),
    ),
    mainPanel(
        tabsetPanel(
                    tabPanel("Original Data", tableOutput("orig_data"))
        )
    )
))


#server.R

library(shiny)

shinyServer(function(input, output, session) {

    ra_dec_data <- reactive({
            if(input$upload_data==0)
                    return(NULL)

            return(isolate({
                    head(read_data(input$in_file$datapath, input$in_file$is_header), 50)
            }))
    })

    output$orig_data <- renderTable({
        ra_dec_data()
    })
})
Run Code Online (Sandbox Code Playgroud)

我面临的问题是,文件一旦被选中就会上传,并且上传按钮没有响应.

我的猜测是我所做的事情没有意义,所以请接受我的道歉,因为这样做非常糟糕.任何帮助将非常感激.谢谢!

Jul*_*rre 6

fileInput 直接上传文件,所以我建议你创建自己的"fileInput".

以下是我将如何进行:

Server.R

library(shiny)

shinyServer(function(input, output, session) {

  observe({

    if (input$browse == 0) return()

    updateTextInput(session, "path",  value = file.choose())
  })

  contentInput <- reactive({ 

    if(input$upload == 0) return()

    isolate({
      writeLines(paste(readLines(input$path), collapse = "\n"))
    })
  })

  output$content <- renderPrint({
    contentInput()
  })

})
Run Code Online (Sandbox Code Playgroud)

Ui.R

library(shiny)

shinyUI(pageWithSidebar(

  headerPanel("Example"),

  sidebarPanel(
    textInput("path", "File:"),
    actionButton("browse", "Browse"),
    tags$br(),
    actionButton("upload", "Upload Data")
  ),

  mainPanel(
    verbatimTextOutput('content')
  )

))
Run Code Online (Sandbox Code Playgroud)

在"Server.R"中,首先我们在每次单击操作按钮"Browse"时更新文本输入的值.

"contentInput"是一个反应函数,它将在输入值(包含在函数体中)被更改时重新执行,"input $ upload"在这里,而不是当"input $ path"因为我们隔离它而改变时.如果我们没有隔离包含"input $ path"的部分,那么每次浏览新文件时都会重新执行"contentInput",然后上传按钮在此处无用.

然后我们在"output $ content"中返回"contentInput"的结果.

希望这有帮助.

编辑##:

我意识到如果你取消文件选择它会产生错误并且闪亮的应用程序崩溃,那么你应该使用Henrik Bengtsson的这个功能(https://stat.ethz.ch/pipermail/r-help/2007-June/133564 .html):

file.choose2 <- function(...) {
  pathname <- NULL;
  tryCatch({
    pathname <- file.choose();
  }, error = function(ex) {
  })
  pathname;
}
Run Code Online (Sandbox Code Playgroud)

  • 重要的是,只有在本地运行Shiny应用程序时,file.choose才会起作用.我不确定你的意思是'直接上传文件'. (2认同)
  • OP 希望“使用 fileInput 选择一个文件,然后仅在单击“上传”按钮时上传它。” `fileInput` 不会等待用户操作来上传数据。 (2认同)