R shiny app(Gallery app) that lets user upload multiple images and display them dynamically(multiple images ,like a grid)

I am very new to R and R shiny and am only learning about it.I've hit a brick wall. I want to build an app that lets user upload images(Saved locally on computer).The uploaded images need to be displayed in the mainpanel() dynamically.

I have used fileInput() to let user upload the image in ui. In server section I have used observeEvent() to complete uploading and renderUI() to display.But it dosn't work. It shows Error:RAW() can only be applied to a 'raw', not a 'character'.

CODE I have so far:

ui <- fluidPage
(sidebarLayout(
  sidebarPanel(
    fluidRow( 
      fileInput("myFile", "Choose a file", accept = c('image/png', 'image/jpeg'))
    )
  ),
  mainPanel(
    uiOutput("images")
),
)
)


server <- function(input, output) {
   observeEvent(input$myFile, {
      inFile <- input$myFile
   if (is.null(inFile))
      return()
file.copy(inFile$datapath,file.path("/Users/rohith/Desktop/PROJECTS AND WORK FILES/trial&error/coommoninlist/images", inFile$name) )


})
output$images <- renderUI({

b64 <- list() #to do base64 encoding
for (i in list.files()) {
   name <- paste('image:', i, sep = '')
   tmp <- base64enc::dataURI(file = i, mime = "image/png")
   b64[[name]] <- tmp
 }

 a64 <- list()
 for (j in (1:length(b64))) {
   name_1 <- paste('img:', j, sep = '')
   tmp_1 <- img(src = b64[j],
                width = 250,
                height = 250)
   a64[[name_1]] <- tmp_1
 }
 a64
 # Output list of images
  })
} 
shinyApp(ui = ui, server = server)

Any Help would be appreciated..:innocent::smiley:

I would do it this way...in general, try to avoid copying files to absolute paths (that file.copy() wouldn't work on any machine but your own)

library(shiny)

ui <- fluidPage(
  sidebarLayout(
  sidebarPanel(
    fluidRow( 
      fileInput("myFile", "Choose a file", accept = c('image/png', 'image/jpeg'))
    )
  ),
  mainPanel(
    div(id = "image-container", style = "display:flexbox")
  )
)
)


server <- function(input, output) {
  
  observeEvent(input$myFile, {
    inFile <- input$myFile
    if (is.null(inFile))
      return()
    
    b64 <- base64enc::dataURI(file = inFile$datapath, mime = "image/png")
    insertUI(
      selector = "#image-container",
      where = "afterBegin",
      ui = img(src = b64, width = 250, height = 250)
    )
  })
  
} 
shinyApp(ui = ui, server = server)
1 Like

Thanks man , for the help.This works.But the I don't want the images to go when the app is refreshed. i.e just like a gallery app in a smart phone.So shouldn't the file.copy() be used?

I would use one of the approaches mentioned in this article instead https://shiny.rstudio.com/articles/persistent-data-storage.html

2 Likes

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.