I am making an app which can generate plots from input and it has no problem showing it on the UI but when I try to zip it by putting them into a temporary directory using ggsave() and use zip(), it doesn't work.
The example I have here generated the plot file in the temporary directory, but no zip file was generated. There is an extra directory in the temp dir which makes me think it has tried the process but somehow stopped.
Here is my code:
library(tidyverse)
library(shiny)
data(iris)
write.csv(iris,"C:/Users/User/Downloads/iris.csv") # I generated this file as input for the app to work
#UI
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File", accept = ".csv"), # input button
downloadButton("dl", label = "Download zip!") #download button
),
mainPanel(plotOutput("plot")) # showing the plot
)
)
server <- function(input, output, session) {
# read input file
up_res <- reactive({
inFile <- input$file1
if (is.null(inFile)) {
return(NULL)
}
read.csv(inFile$datapath)
})
# generate plot
output$plot <- renderPlot({
g <<- ggplot(up_res(), aes(x = Sepal.Length, y = Petal.Length)) +
geom_dotplot(binaxis='y', stackdir='center')
return(g)
})
# supposed to create zip file containing png file of plot
output$dl <- downloadHandler(
filename = function() {
paste('iris-', Sys.Date(), '.zip', sep='')
},
content = function(comp) {
owd <- setwd(tempdir())
on.exit(setwd(owd))
ggsave("iris.png",plot = g, device = "png")
zip(zipfile = comp, files = "iris.png")
if(file.exists(paste0(comp,".zip"))) {file.rename(paste0(comp, ".zip"), comp)}
#this is added as advised online zip may have read the pathway name wrongly from downloadHandler's content argument. but omitting it or not the results are the same
}
)
}
shinyApp(ui = ui, server = server)