Wednesday 9 August 2023

How to handle if no file is uploaded in Shiny App

I am working on a Shiny application that includes three main features:

  • Uploading an .xlsx file.

  • Processing the uploaded file when a Process button is clicked.

  • Downloading the .xlsx file when a Download button is clicked.

But the above buttons needs to be based on two conditions:

  • When a user tries to click the Download button without uploading a file, a pop up message should show.
  • If the user uploads a file but clicks the Download button without first clicking the "Process" button, the application should display a pop-up message.
  • if all above conditions are met and Download button is pressed then xlsx file should be downloaded

In my current implementation, the pop-up message does not display when the Download button is clicked without first uploading a file. However, after a file is uploaded, clicking the 'Download' button does work as expected. In addition to that, process button condition is also not added.

My sample Code:

library(shiny)
library(readxl)
library(tidyverse)

library(writexl)

library(bsplus)

library(shinyalert)
library(shinyjs)
library(lubridate)

ui <- fluidPage(
  useShinyjs(),
  titlePanel("Regularizer 15 min"),
  tags$div(id = "sidebar",
           sidebarPanel(
             bs_accordion(
               id = "accordion"
             ) %>%  
               bs_set_opts(
                 use_heading_link = TRUE
               ) %>%  
               bs_append(
                 title = tags$div(tags$i(class = "fa-solid fa-upload"),"Upload"),
                 content = fileInput("upload", "Upload a Excel File",  
                                     accept = c(".xlsx",".csv"))
               ),
             actionButton("act_button1", "Process"), # You may need to specify the action of this button
             use_bs_accordion_sidebar()
           )),
  mainPanel(id = "mainPanel",
            tags$div(class = "download-btn",
                     downloadButton("downloadData_all", "Download Regularized ")
            )
  )
)

server <- function(input, output, session) {
  
  options(shiny.maxRequestSize = 100*1024^2)
  
  session$onSessionEnded(function() {
    stopApp()
  })
  
  observeEvent(input$downloadData_all, {
    if (is.null(input$upload)){
      showModal(modalDialog(
        title = "Error",
        "Click Process ",
        footer = NULL, easyClose = TRUE
      ))
    } 
  })
  
  output$downloadData_all <- downloadHandler(
    filename = function() {
      file_name <- input$upload$name
      paste("regularised_", file_name, ".xlsx", sep = "")
    },
    content = function(file) {
      req(input$upload)
      
      data <- readxl::read_excel(input$upload$datapath, sheet = 1)
      
      
      writexl::write_xlsx(data, path = file)
    }
  )
}

shinyApp(ui,  server)


from How to handle if no file is uploaded in Shiny App

No comments:

Post a Comment