I have been trying to solve a problem in developing one of my first R Shiny apps. My app works on my laptop, but I can't get it to work when I upload it on the Shiny server. I want the app to create a temporary file of the scatterplot, plotOut, on the server, which is then exported to the Excel file, either upon clicking the 'Download Scatterplot' button or automatically. I am posting my best attempt at a reprex below. I believe I need to use tempdir() in some way, but not sure how. Thanks in advance :D
"ui.R"
library(tidyverse)
library(openxlsx)
ui <- fluidPage(
fluidRow("This is a simplified app to reproduce the difficulties in saving and downloading files on the Shiny server",
plotOutput("plot", height = 350),
downloadButton('downloadPlot1', "Download ScatterPlot"),
downloadButton(
'dl_excel',
'Download Results (.xlsx)'
)
)
)
"server.R"
server <- function(input, output){
###create basic plot in ggplot
plotOut <- reactive(
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
)
###display plot
output$plot <- renderPlot({
plotOut()
})
#temp = tempdir() #tried using this in filename to no avail
fName = paste0('plotOut', Sys.Date(), '.png')
##save plot file as png
output$downloadPlot1 <- downloadHandler(
filename = function(){fName},
content = function(file){
ggsave(file,plot=plotOut())
})
##format excel file for output
output$dl_excel <- downloadHandler(
filename = function(){
paste0('results_', Sys.Date(), '.xlsx')
},
content = function(file){
my_workbook <- createWorkbook()
addWorksheet(
wb = my_workbook,
sheetName = "Sheet1"
)
insertImage(my_workbook, sheet = 1,
file = fName
, width = 4, height = 4, startRow = 1, startCol = 1, units = "in", dpi = 300
)
saveWorkbook(my_workbook, file)
}
)
}
Someone in a different forum helped me solve this. Updating the code to the following resolves the issue.
output$dl_excel <-
downloadHandler(
filename = function() {
paste0('results_', Sys.Date(), '.xlsx')
},
content = function(file) {
**tempPNG <- tempfile(fileext = ".png") #create a tempfile to print the plot to
ggsave(tempPNG, plot = plotOut()) #print the plot to the tempfile**
my_workbook <-
createWorkbook()
addWorksheet(wb = my_workbook,
sheetName = "Sheet1")
insertImage(
my_workbook,
sheet = 1,
**file = tempPNG, #use the tempfile**
width = 4,
height = 4,
startRow = 1,
startCol = 1,
units = "in",
dpi = 300
)
saveWorkbook(my_workbook, file)
}
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.