首页 > 解决方案 > 将用户上传的文件存储到指定的本地文件夹

问题描述

我想创建一个应用程序,用户 A 将文件上传到服务器,用户 B 可以将其下载到本地文件夹。我首先实现上传文件的操作,然后立即将该文件存储到我自己指定的文件夹中(因为我是这里的唯一用户)。这是代码:

library(shiny)

ui <- fluidPage(
    fileInput('file1', 'Choose csv File',
              accept=c('text/csv'))
)

server <- function(input , output){
    rootDir <- 'C:/RShiny/Dir'  
    inFile <- reactive({input$file1})

    file.copy(inFile()$datapath,
               file.path(rootDir, inFile()$name, fsep = .Platform$file.sep))
}

shinyApp(ui = ui , server = server)

但是,我不断收到此错误消息:

Warning: Error in .getReactiveEnvironment()$currentContext: Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
  53: stop
  52: .getReactiveEnvironment()$currentContext
  51: getCurrentContext
  50: .dependents$register
  49: inFile
  47: server [C:\RShiny\.../app.R#12]
Error in .getReactiveEnvironment()$currentContext() : 
  Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

该应用程序立即关闭。不知道这意味着什么以及如何解决它。如果有人可以帮助解释?

谢谢,

标签: rshinyshiny-reactivity

解决方案


请尝试以下方法:

library(shiny)

ui <- fluidPage(
    fileInput('file1', 'Choose csv File',
              accept=c('text/csv'))
)

server <- function(input , output){
    rootDir <- 'C:/RShiny/Dir'  
    inFile <- reactive({input$file1})

    observe({
        file.copy(inFile()$datapath,
              file.path(rootDir, inFile()$name, fsep = .Platform$file.sep))
    })
}

shinyApp(ui = ui , server = server)

您需要将file.copy()代码放在observe(“反应式表达式或观察者”)中。


推荐阅读