My "download" button does not work as expectation. It opens a new app window every time I click on it. I am wondering why it functions in this way?
download function in server.R:
output$down_load <- downloadHandler(
# specify the file name
filename = function() {
paste('cls_result_export', Sys.Data(),'.csv', sep='')
},
# Write the plot back
content = function(file){
write.csv(cls_output()$raw_data, file)
}
)
download function in ui.R:
downloadButton(outputId = "down_load", label = "Download the CLS Raw Data")
Try using an actionButton wired to an observe clause like this:
library(shiny)
ui <- fluidPage( actionButton("dodo", "Download" ) )
server <- function(input, output)
{
observe({
if (input$dodo>0){
fname <- paste0('cls_result_export', Sys.Date(),'.csv')
write.csv(mtcars,fname)
}
})
}
shinyApp(ui = ui, server = server)
Another possible way to try to fix this issue, is to include this line in your server.R script:
outputOptions(output, 'down_load', suspendWhenHidden=FALSE)
Related
The scenario I'm emulating with the below minimal example is allowing a user to engage with a Shiny App (click the numericInput control and see server-side events occur) while a long-running download is occurring (simulated with Sys.sleep(10) within downloadHandler).
In a synchronous setting, when the "Download" button is clicked, the user can still interact with UI elements, but other Shiny calculations (in this case, renderText), get put in a queue. I'd like the asynchronous setting, where the download occurs in the background, and users can still interact with the UI elements and get desired output (e.g. renderText).
I'm using callr::r_bg() to achieve asynchronicity within Shiny, but the issue is that my current code of the downloadHandler is incorrect (mtcars should be getting downloaded, but the code is unable to complete the download, 404 error message), I believe it's due to the specific way in which downloadHandler expects the content() function to be written, and the way I've written callr::r_bg() is not playing nicely with that. Any insights would be appreciated!
Reference:
https://www.r-bloggers.com/2020/04/asynchronous-background-execution-in-shiny-using-callr/
Minimal Example:
library(shiny)
ui <- fluidPage(
downloadButton("download", "Download"),
numericInput("count",
NULL,
1,
step = 1),
textOutput("text")
)
server <- function(input, output, session) {
long_download <- function(file) {
Sys.sleep(10)
write.csv(mtcars, file)
}
output$download <- downloadHandler(
filename = "data.csv",
content = function(file) {
x <- callr::r_bg(
func = long_download,
args = list(file)
)
return(x)
}
)
observeEvent(input$count, {
output$text <- renderText({
paste(input$count)
})
})
}
shinyApp(ui, server)
I figured out a solution, and learned the following things:
Because downloadHandler doesn't have a traditional input$X, it can be difficult to include reactivity in the traditional way. The workaround was to present the UI as a hidden downlodButton masked by an actionButton which the user would see. Reactivity was facilitated in the following process: user clicks actionButton -> reactive updates -> when the reactive finishes (reactive()$is_alive() == FALSE), use shinyjs::click to initiate the downloadHandler
Instead of placing the callr function within the downloadHandler, I kept the file within the content arg. There seems to be some difficulties with scoping because the file needs to be available within the content function environment
I'm using a reactive function to track when the background job (the long-running computation) is finished to initiate the download using the syntax: reactive()$is_alive()
The invalidateLater() and toggling of a global variable (download_once) is important to prevent the reactive from constantly activating. Without it, what will happen is your browser will continually download files ad infinitum -- this behavior is scary and will appear virus-like to your Shiny app users!
Note that setting global variables is not a best practice for Shiny apps (will think of a better implementation)
Code Solution:
library(shiny)
library(callr)
library(shinyjs)
ui <- fluidPage(
shinyjs::useShinyjs(),
#creating a hidden download button, since callr requires an input$,
#but downloadButton does not natively have an input$
actionButton("start", "Start Long Download", icon = icon("download")),
downloadButton("download", "Download", style = "visibility:hidden;"),
p("You can still interact with app during computation"),
numericInput("count",
NULL,
1,
step = 1),
textOutput("text"),
textOutput("did_it_work")
)
long_job <- function() {
Sys.sleep(5)
}
server <- function(input, output, session) {
#start async task which waits 5 sec then virtually clicks download
long_run <- eventReactive(input$start, {
#r_bg by default sets env of function to .GlobalEnv
x <- callr::r_bg(
func = long_job,
supervise = TRUE
)
return(x)
})
#desired output = download of mtcars file
output$download <- downloadHandler(filename = "test.csv",
content = function(file) {
write.csv(mtcars, file)
})
#output that's meant to let user know they can still interact with app
output$text <- renderText({
paste(input$count)
})
download_once <- TRUE
#output that tracks progress of background task
check <- reactive({
invalidateLater(millis = 1000, session = session)
if (long_run()$is_alive()) {
x <- "Job running in background"
} else {
x <- "Async job in background completed"
if(isTRUE(download_once)) {
shinyjs::click("download")
download_once <<- FALSE
}
invalidateLater(millis = 1, session = session)
}
return(x)
})
output$did_it_work <- renderText({
check()
})
}
shinyApp(ui, server)
Thanks #latlio for your great answer. I think it cloud be easily improved.
invalidateLater should be used very carefully and only WHEN needed. I use invalidateLater only once and moved it to the logical part where we are waiting for the result. Thus we are NOT invalidating the reactivity infinitely.
library(shiny)
library(callr)
library(shinyjs)
ui <- fluidPage(
shinyjs::useShinyjs(),
#creating a hidden download button, since callr requires an input$,
#but downloadButton does not natively have an input$
actionButton("start", "Start Long Download", icon = icon("download")),
downloadButton("download", "Download", style = "visibility:hidden;"),
p("You can still interact with app during computation"),
numericInput("count",
NULL,
1,
step = 1),
textOutput("text"),
textOutput("did_it_work")
)
long_job <- function() {
Sys.sleep(5)
}
server <- function(input, output, session) {
#start async task which waits 5 sec then virtually clicks download
long_run <- eventReactive(input$start, {
#r_bg by default sets env of function to .GlobalEnv
x <- callr::r_bg(
func = long_job,
supervise = TRUE
)
return(x)
})
#desired output = download of mtcars file
output$download <- downloadHandler(filename = "test.csv",
content = function(file) {
write.csv(mtcars, file)
})
#output that's meant to let user know they can still interact with app
output$text <- renderText({
paste(input$count)
})
#output that tracks progress of background task
check <- reactive({
if (long_run()$is_alive()) {
x <- "Job running in background"
invalidateLater(millis = 1000, session = session)
} else {
x <- "Async job in background completed"
shinyjs::click("download")
}
return(x)
})
output$did_it_work <- renderText({
check()
})
}
shinyApp(ui, server)
I'm building a Shiny App where users complete a survey, and based on their responses, it suggests different templates for them to use. The templates are all excel files that are heavily formatted (e.g., have pictures on them, misaligned headings, etc.), like the screenshot that I've uploaded here. Unfortunately, stackoverflow won't let me upload the excel file to make this fully reproducible, but if you can run it with any non-tabular excel file, it'll work.[![enter image description here][1]][1]
These templates are all uploaded to the server, and the users input does not affect them. I've tried following the example by others, like this [one][2], but I keep getting errors.
How do I get it so when users click the download button, they get the excel file exactly as it appears?
library(readxl)
library(shiny)
library(writexl)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(
downloadButton("downloadData", "Download Fancy Excel File")
)))
server <- function(input, output) {
output$downloadData <- downloadHandler(
filename = function() {
paste("file", "xlsx", sep='')
},
content = function(file) {
myfile <- srcpath <- 'Home/Other Layer/Fancy Template.xlsx'
file.copy(myfile, file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
~~~~
[1]: https://i.stack.imgur.com/FK034.png
[2]: https://stackoverflow.com/questions/39449544/shiny-download-an-excel-file
You are missing a . in the file name. Also, you can keep all the files you want the users to download in www folder. The following works for me.
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(
downloadButton("downloadData", "Download Fancy Excel File")
)))
server <- function(input, output) {
output$downloadData <- downloadHandler(
filename = function() {
paste("testfile", ".xlsx", sep='')
},
content = function(file) {
# myfile <- srcpath <- 'Home/Other Layer/Fancy Template.xlsx'
myfile <- srcpath <- "./www/test141.xlsx"
file.copy(myfile, file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
I have met an issue when I try to implement a download button in Shiny App. Every time I run the app, it will only show me an HTML file not the actual content file. Here is my code for both the server and UI parts.
library(shiny)
library(reticulate)
shinyServer(function(input,output){
reticulate::source_python("function.py")
data_xi <- run_xi(26)
output$downloadData <- downloadHandler(
filename = function(){
paste(Sys.time(), 'site_mtx.xlsx')
},
content = function(file){
write_xlsx(data_xi, file)
}
)
})
Here is the UI:
library(shiny)
shinyUI(fluidPage(
downloadButton("downloadData", "Download Metrics Reports")
))
I just tried to use the reticulate function in my python file and save the processed dataframe to Shiny App which can be downloads, thank you very much!
I ran an example out of your code with some adjustions (unfortunately i don't have your file) and it downloads normally a xlsx file. Add the data.frame( run_xi(26))and if this is not the problem maybe the "writexl" library can be the solution.
Hope it will help.
library(shiny)
library(reticulate)
library(writexl)
if (interactive()) {
ui <-fluidPage(
downloadButton("downloadData", "Download Metrics Reports")
)
server <- function(input,output){
data_xi <- data.frame(s = c(1:3),r = c(4:6), x =c(19:21))
output$downloadData <- downloadHandler(
filename = function(){
paste(Sys.time(), 'site_mtx.xlsx')
},
content = function(file){
write_xlsx(data_xi, file)
}
)
}
shinyApp(ui, server)
}
I'm building an app that operates regularly when nothing is given in a url query, however if a certain string is given there it should download the file immediately. The download works fine, but when it is run at start up it return a 'download.htm' file instead of the .csv. The reproducible example is not querying the url, but triggers in an observe:
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs()
,downloadButton("downloadData", "Download")
)
server <- function(input, output) {
data <- mtcars
observe({
print("click MacClickFace")
runjs("document.getElementById('downloadData').click();")
})
output$downloadData <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(data, file)
}
)
}
shinyApp(ui, server)
How can you trigger the download at launch or are there some security things going on here?
Probably the downloadHandler is not ready. You can use a setTimeout(..., 0):
runjs("setTimeout(function(){document.getElementById('downloadData').click();},0);")
I have a Shiny downloadHandler
in server.R:
output$DownloadButton <- downloadHandler(
filename = function() {
paste("test", Sys.Date(), ".csv",sep="")
},
content = function(con) {
print("in download")
print(con) # this prints C:\\Users\\me\\Local\\Temp\\RtmpI1EjY7\\file668338e4c33
Data<-ReactiveGetData()$Data #Here I get the data I want to download
print(head(Data)) #This prints out the data with no errors
write.csv(Data, con)
}
)
here is ui.r:
sidebarPanel(
downloadButton("DownloadButton", label = "Download",class = NULL), ....
So far it printed the temp file:
C:\\Users\\me\\Local\\Temp\\RtmpI1EjY7\\file668338e4c33
BUT When I go to this path manually I get an error saying "File not found"
and then when I click on the download button I do not get an error and nothing happens.
Any idea why the temp file doesn't seem to be created?
Should the temp file end in csv?
HERE IS AN EVER SIMPLER EXAMPLE which you can run if you run the server.r and ui.r files belwo. I cannot download the file below:
The "file" object does not exist below any idea why?
ui.r
library(shiny)
shinyUI(fluidPage(
sidebarPanel(
downloadButton("Download", label = "Download",class = NULL)
),
mainPanel(
tabsetPanel(
tabPanel("test",
h3("test")
)
)
)
))
server.r
library(rJava)
shinyServer(function(input, output, session) {
output$Download <- downloadHandler(
filename = function() {
paste("test.csv",sep="")
},
content = function(file) {
print("in download")
print(file) #this file does not exist ???
Data<- data.frame(name= c(1,2,3,4))
print(head(Data))
write.csv(Data, file)
}
)
})#end of server function
you can run this by:
library(rJava)
library(shiny)
runApp("C://Users//me//pathToShinyProjectFolder")
SOULTION: click "open in browser" in upper left and user CHROME OR FIREFOX as default browser.
Try opening the application in another browser. Not all browsers are created equally. This can be done by simply typing the following in another browser of your choosing.
localhost:5586
Note, that the port number may be different for you.