r-在downloadHandler中作为文件名的反应元素



如何使用反应函数中的元素作为downloadHandler中的文件名?在这个例子中,我允许用户上传一个.csv,一个新列被添加到data.frame中,然后我希望用户能够以.csv的形式返回修改后的data.frame.如果我硬编码文件名,它会像我预期的那样工作。但我希望返回文件的名称与输入文件相同,但带有后缀。将文件名指定为反应函数fileInfoFn的元素之一,会返回官样文章,如"_tmp_Rtmp574nlm_5fcb74621d7eebf0d0ab5bb1_0.csv_mod.csv">

ui <- fluidPage (
helpText("Click here to upload file"),
fileInput(inputId = "importedFile",
label = NULL,
accept = c(".csv"),
buttonLabel = "Upload File",
placeholder = "NA"),
helpText("Click here to download output"),
downloadButton(outputId = "exportedOutput",
label = "Download Output"))
server <- function(input, output) {
fileInfoFn <- reactive ( {
inFile <- input$importedFile
if (is.null(inFile)) {
return(NULL)
} else {
file.rename(inFile$datapath,
paste(inFile$datapath, ".csv", sep=""))
fileInfo <- list(
outFile = paste0(inFile$datapath, "_mod.csv"),
fileData = read.csv(paste(inFile$datapath, ".csv", sep=""))
)
return(fileInfo)
}
} )

produceOutput <- reactive( {
fileInfo <- fileInfoFn()
if (length(fileInfo) > 0){
dat4 <- fileInfo[["fileData"]]
dat4$newColumn <- 1
} else {
dat4 <- data.frame(x = "noData")
}
return(dat4)
} )

output$exportedOutput <- exportedOutput <- downloadHandler(
filename = function() {
fileInfo <- fileInfoFn()
if ("outFile" %in% names(fileInfo)) {
outFile <- fileInfo[["outFile"]] # hard-coded value, like "userMod.csv," works
} else {
outFile <- "default.csv"
}
return(outFile)
},
content = function(file){
write.csv(produceOutput(), file)
}
)
}
shinyApp(ui = ui, server = server)

试试这个

ui <- fluidPage (
helpText("Click here to upload file"),
fileInput(inputId = "importedFile",
label = NULL,
accept = c(".csv"),
buttonLabel = "Upload File",
placeholder = "NA"),
helpText("Click here to download output"),
downloadButton(outputId = "exportedOutput",
label = "Download Output")
,verbatimTextOutput("t1")
)
server <- function(input, output) {
fileInfoFn <- reactive ( {
inFile <- input$importedFile
if (is.null(inFile)) {
return(NULL)
} else {
# file.rename(inFile$datapath,
#             paste(inFile$datapath, ".csv", sep=""))
fname <- substr(inFile, 1, nchar(inFile)-4)
return(list(
outFile = paste0(fname, "_mod.csv"),
fileData = read.csv(inFile$datapath, header=TRUE, sep=",")
))
}
} )
output$t1 <- renderPrint({fileInfoFn()$fileData})

produceOutput <- reactive( {
fileInfo <- fileInfoFn()
if (length(fileInfo) > 0){
dat4 <- fileInfoFn()$fileData
dat4$newColumn <- 1
} else {
dat4 <- data.frame(x = "noData")
}
return(dat4)
} )

output$exportedOutput <-  downloadHandler(
filename = function() {
fileInfo <- fileInfoFn()
if ("outFile" %in% names(fileInfo)) {
outFile <- fileInfoFn()$outFile[1] # hard-coded value, like "userMod.csv," works
} else {
outFile <- "default.csv"
}
return(outFile)
},
content = function(file){
write.csv(produceOutput(), file)
}
)
}
shinyApp(ui = ui, server = server)

相关内容

最新更新