我在 Shiny 应用程序中生成并显示一个 flextable 并想将它放在 PDF 中。唯一可用的方法是将 flextable 对象转换为 PNG,然后将 PNG 放入 PDF。对于每个 PNG 文件,我分配了一个包含日期时间戳的文件名,以使其在 session 之间是唯一的。这个文件名保存在一个reactiveValue 中。
当用户完成并关闭 session 时,如何删除文件?如果我不这样做,我会堆积无关的文件。我不能使用 onSessionEnded() 因为当浏览器关闭时 react 值都消失了。我无法使用模式进行概括,因为其他用户有具有相似名称的文件。我必须专门删除这些PNG文件。
有任何想法吗?
不起作用的 onSessionEnded 代码:
observe({
session$onSessionEnded(function() {
unlink(c(values$fnameSummary))
unlink(c(values$fnameLike))
unlink(c(values$fnameRisk1))
})
})
这会产生以下错误:
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.)
Stack trace (innermost first):
33: .getReactiveEnvironment()$currentContext
32: .subset2(x, "impl")$get
31: $.reactivevalues
30: $
29: unlink
28: callback [C:\Users\jch1748\Documents\Projects\W2017010 - Combined Risk Tool\testing/server.R#2790]
1: runApp
也许一个有效的例子会有所帮助?
#
# 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)
tsts <- reactiveValues()
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
observe({
tsts$fname <- "AAA.txt"
write(input$bins, file=tsts$fname)
})
onSessionEnded(function() {
cat("Session Ended\n")
unlink(tsts$fname)
})
}
# Run the application
shinyApp(ui = ui, server = server)
最佳答案
我有一个类似的问题,我想在一个 Shiny 的应用程序中动态提供图像和 pdf 文件以供下载。因此,文件需要放置在 www 目录中,这使得无法使用 tempdir。此外,应用程序停止后需要删除创建的文件。我用以下代码解决了这个问题:
session$onSessionEnded(function() {
system(paste("rm -f", PathToFile))
})
关于r - 如何在 session 关闭时删除 Shiny 应用程序创建的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49178159/