Why my download button is not working?

I want to download my plot into png or pdf formate .
here code for UI:

library(shiny)

shinyUI(fluidPage(
  titlePanel(title=h3("Iris Dataset Shiny App",align="center")),
  sidebarLayout(
    sidebarPanel(
      selectInput("x_axis","Select Variable", 
                  choices = c("Sepal.Length"=1,"Sepal.Width"=2,
                              "Petal.Length"=3,"Petal.Width"=4)),
     br(),
     selectInput("y_axis","Select Variable", 
                 choices = c("Sepal.Length"=1,"Sepal.Width"=2,
                             "Petal.Length"=3,"Petal.Width"=4)),
     br(),
    radioButtons("fileType","Choose file type",
                 choices = c("png","pdf"),selected = "png")
       
    ),
    mainPanel(
      plotOutput("plot"),
      downloadButton(outputId="downloadBtn",label="Download the file")
    )
  )
))

Here code for server:

library(shiny)

shinyServer(
  function(input,output){
    x <- reactive({
      iris[,as.numeric(input$x_axis)]
    })
    
    y <- reactive({
      iris[,as.numeric(input$y_axis)]
    })
    
    output$plot <- renderPlot({
      plot(x(),y())
    })
    
    
    output$downloadBtn <- downloadHandler(
      filename = function(){
        paste("iris",input$fileType,sep = ".")
      },
      content = function(file){
        if(input$fileType=="png")
          png(file)
        else
          pdf(file)
        plot(x(),y())
        dev.off()
      }
    )
  
  }
)

try wrapping your plot call in print()

content = function(file){
        if(input$fileType=="png")
          png(file)
        else
          pdf(file)
        print(plot(x(),y()))
        dev.off()
      }

still not working , it open in a file browser but doesn't save as a correct file format. File is shown invalid here

what is filename when you download?

Filename is " downloadBtn"
But it should be iris.png

Have you tried running this in a web browser? The R Studio viewer doesn't always behave the same way with downloads. When I run your app in Chrome, the file downloads just fine.

2 Likes

ah yes the download button does not work in the RStudio viewer. If you open the app in a browser the file will download appropriately.

2 Likes

yes you are right . it is working now .