J0k*_*0ki 3 r temporary-files shiny
我正在开发一个闪亮的应用程序,用户可以上传文件并选择 X 参数,然后按下按钮,它会生成 5 个图(ggplot2 和 barplot)以及动态数据表(DT)。另外,我想将我闪亮的应用程序放入 Linux 服务器中。
我用于tempfiles()创建绘图和 DT 的每个文件。
之后,我的问题是:
当用户关闭闪亮的应用程序(关闭窗口)时,临时文件会自动删除吗?
如果没有,我该怎么做才能删除临时文件?
我的尝试:
session$onSessionEnded(function() {
if (!is.null(x1)) {
file.remove(x1)
}
if (!is.null(x2)) {
file.remove(x2)
}
if (!is.null(x3)) {
file.remove(x3)
}
if (!is.null(x4)) {
file.remove(x4)
}
if (!is.null(xx)) {
file.remove(xx)
}
})
Run Code Online (Sandbox Code Playgroud)
或者:
session$onSessionEnded(function() {
files <- list.files(tempdir(), full.names = T, pattern = "^file")
file.remove(files)
})
Run Code Online (Sandbox Code Playgroud)
使用该代码,当用户按下按钮一次时,我会删除临时文件,如果用户按下按钮超过 1 次,则窗口将关闭,并且只会删除最后生成的文件。第二部分删除临时目录中的所有文件,但这会影响其他用户?(我认为是的,这就是为什么我需要另一个解决方案)。
ggplot 和 barplot 生成的 .png 临时文件不会自动删除。
我担心的是,如果临时文件不会自动删除,Linux 服务器会因为大量临时文件而崩溃。
希望你能解答我的疑惑。阿特·琼.
deleteFile=TRUE如果您想要一个render函数自动删除临时文件,您可以使用该参数:
shinyServer(function(input, output, clientData) {
output$myImage <- renderImage({
# A temp file to save the output.
# This file will be removed later by renderImage
outfile <- tempfile(fileext='.png')
# Generate the PNG
png(outfile, width=400, height=300)
hist(rnorm(input$obs), main="Generated in renderImage()")
dev.off()
# Return a list containing the filename
list(src = outfile,
contentType = 'image/png',
width = 400,
height = 300,
alt = "This is alternate text")
}, deleteFile = TRUE)
})
Run Code Online (Sandbox Code Playgroud)
创建一个临时文件来保存输出,并且该文件稍后会因deleteFile=TRUE参数而自动删除。
默认的 Shiny ( shiny.R) 还具有一个内置机制,可以清除文件上传目录(如果您担心的话)。以下代码在会话结束时删除上传目录:
registerSessionEndCallbacks = function() {
# This is to be called from the initialization. It registers functions
# that are called when a session ends.
# Clear file upload directories, if present
self$onSessionEnded(private$fileUploadContext$rmUploadDirs)
}
Run Code Online (Sandbox Code Playgroud)
关于手动删除临时文件的另一点(正如您所尝试的那样):每次用户切换到另一个选项卡或调整他/她的浏览器窗口大小时,绘图都必须渲染,因此如果您手动删除文件,它可能会效率低下,因为需要再次重新渲染。该onSessionEnded解决方案更好,因为它确认会话已结束。
session$onSessionEnded(function() {
if (!is.null(input$file1)) {
file.remove(input$file1$datapath)
}
})
Run Code Online (Sandbox Code Playgroud)