Rendering A Local Image File in Shiny - r

I am trying to render a local image file onto the Shiny app interface using a snippet of the example code provided by Shiny website below:
ui <- fluidPage(
imageOutput("plot3")
)
server <- function(input, output, session) {
# Send a pre-rendered image, and don't delete the image after sending it
# NOTE: For this example to work, it would require files in a subdirectory
# named images/
output$plot3 <- renderImage({
filename <- normalizePath(file.path('./images',
paste('image', '2', '.jpeg', sep='')))
# Return a list containing the filename
list(src = filename, alt = "Alternate text")
}, deleteFile = FALSE)
}
shinyApp(ui, server)
It didn't work when I ran the application. However when I added back the interactive() function that was originally in the example code, encase the main code body, I was able to display the local image file without any problems.
if (interactive()) {
ui <- fluidPage(
imageOutput("plot3")
)
server <- function(input, output, session) {...
}
This puzzles me as many of Shiny's tutorials and demonstrations showed rendering can be done without encasing the code body in a scope.
Is there anyone who encounter a similar scenario such as this? Rendering a local image file into a Shiny app?

I just discovered what was wrong with the code through trial and error. The directory which the shiny code app is saved in a different location from the location where the image file is saved. So the solution is either to place a setwd([www image folder location]) or relocate image folder www to where the shiny app resides which it worked - the image is successfully rendered.

Related

Image displayed when app used locally but not working after deployment to Shinyapp.io

I am trying to get an image to display in my shiny app based on a user selection by clicking points on a map that display the photos’ location. The app works fine and displays the photo when I use the app locally via Rstudio but the photo does not display when I deploy the app to shinyapp.io. I believe the problem is that the fpath is not annotated correctly to reach the image but I am not sure what the path should read to reach the image when deployed to shinyapp.io.
I have tried a number of solutions including:
As per think link, I saved copies of the images to both the base folder that holds the app file and the www folder thinking that shiny might automatically look in the www folder since that is where images are normally sourced for displaying in the app but that did not work as paste0(dat$PhotoID,".jpg") or paste0(“www”,dat$PhotoID,".jpg") or paste0(“/www”,dat$PhotoID,".jpg") or paste0(“/www/”,dat$PhotoID,".jpg"). When I run the app locally I can access the image using paste0("./",dat$PhotoID,".jpg") or paste0(dat$PhotoID,".jpg")
I tried to link to a “resource folder” but could not find a function for this call nor do I have an Rmd file as per this link.
This link looked useful but altering if a backslash occurred above did not affect the outcome. I also am unfamiliar with relative vs absolute file paths although for apps deployed on shinyapp.io I would expect relative file paths would be the most appropriate.
I have previously used a static image in my app accessed using img(src = "FigureCombo.png") but since I am using an imageOutput() I don’t think that is appropriate.
Does anyone have any advice on how to access stored images when app is deployed to shinyapp.io?
Thanks
Here is the relevant code:
`
ui <- fluidPage(
mainPanel(
imageOutput("myImage", height = "200px"))
)
server <- function(input, output, session) {
output$myImage <- renderImage({
photo <- selected_photo()
if(is.null(photo)) {
return(NULL)
}
else {
list(src = photo,
contentType = 'image/jpg',
width = 300,
height = 400,
style = 'border-style: solid; border-color: red;',
alt = "No point selected yet or that point does not have an image...")
}
}, deleteFile = FALSE)
selected_photo <- reactive({
dat <- reactive_data()
photoid <- input$wsmap_marker_click$id
dat <- dat[dat$PhotoID %in% photoid,]
fpath <- paste0(dat$PhotoID,".jpg") # works when local but not shinyapp.io
return(fpath)
})
}
shinyApp(ui = ui, server = server)
`
To get an idea of the directory structure on an unfamiliar host, you might list the subdirectories of the work directory (as seen by server.R) and log it to your user interface like so:
ui <- fluidPage(
## ...
verbatimTextOutput('log')
## ...
)
server <- function(input, output) {
## ...
output$log <- renderPrint(list.dirs(getwd()))
## ...
}

Make my existent Excel file available for users to download in shiny app

In my app, users should insert some data from an Excel file, but I want to make it possible for them to download one (TesteR.xlsx) in their computer and use it as an example. I have tried to apply this solution but it didn't work, when I click the button it downloads a kinda weird file.
library(shiny)
ui <- fluidPage(
downloadButton("downloadOP", label = "Download")
)
server <- function(input, output){
output$downloadOP <- downloadHandler(
filename = "ph1data",
content = function(file) {
file.copy("www/TesteR.xlsx", file)
}
)
}
shinyApp(ui, server)
I also included the file in a www folder like suggested in the other question, but maybe I am missing something.
Any help would be very much appreciated!
Make sure your www folder is in the same directory as your app.r or server.r/ui.r files. It must be readable by the shiny server.
As you don't state how your app is started/served (from your computer, on a server, what kind of server, using shiny/server, on shinyapps.io, shinyproxy, ...) further advice won't be very useful.
I will also add the file extension to filename = "ph1data.xlsx".
If you add a A tag to your UI, does it work ? (target="self" prevent opening a new tab)
ui <- fluidPage(
downloadButton("downloadOP", label = "Download"),
tags$a("Download", href="TesteR.xlsx", target="self")
)
If you put and image (eg test.jpg) in your www folder and add an IMG tag to your UI, does it show the image ?
ui <- fluidPage(
downloadButton("downloadOP", label = "Download"),
tags$a("Download", href="TesteR.xlsx", target="self", class="btn btn-primary"),
tags$img(src="test.jpg")
)

Where is the local host directory of a shiny app in R to display local pdf file?

I am Looking at this Question: displaying a pdf from a local drive in shiny and want to Display a local pdf file.
I placed my pdf within C:\Users\user1\Documents\shiny_pdf\www. The app is placed in C:\Users\user1\Documents\shiny_pdf and i set my working Directory to the latter Directory.
Now i am unsure on how to reference that file within the app.
The author of the answer post in the linked Question states:
so you have to save them in your www directory (a local web server)
and access to files with their http(s): URLs (the URL will be
something like http://localhost/.../mypdf.pdf)
So i am unsure on how to navigate from http://localhost/ to C:\Users\user1\Documents\shiny_pdf\www.
What i tried:
I would have assumed i have www is the Server Directory so i would use http://localhost/R-intro.pdf.
I added an Image to my shiny app and checked its server address in the browser. Then i located the pdf file accordingly. I can open it via: http://127.0.0.1:6023/r-intro.pdf (with 6023 being my port number). But i cant use that either to reference it in the iframe.
I also tried list.files(), but that would (obv.) give me the files from the working Directory.
http://localhost/R-intro.pdf also does not work.
The error:
Fehler: Verbindung fehlgeschlagen
Firefox kann keine Verbindung zu dem Server unter localhost aufbauen.
which loosely translates to. Connection failed. Firefox can´t make a Connection to the Server under localhost.
Reproducible Code:
Save the following file (see below) as, e.g. app.R.
Run the following Code to create a WWW directoy for shiny and place a sample pdf into it.
dir.create("www")
pdf(file = "www/r-intro.pdf")
plot(1)
dev.off()
list.files()
Here the Code to save in e.g. app.R.
Code:
library(shiny)
server <- shinyServer(function(input, output, session) {
observe({
print(list.files("http://localhost/R-intro.pdf"))
})
output$pdfviewer <- renderText({
return(paste('<iframe style="height:600px; width:100%" src="', input$pdfurl, '"></iframe>', sep = ""))
})
})
row <- function(...) {
tags$div(class="row", ...)
}
col <- function(width, ...) {
tags$div(class=paste0("span", width), ...)
}
ui <- shinyUI(bootstrapPage(
headerPanel("PDF VIEWER"),
mainPanel(
tags$div(
class = "container",
row(
col(3, textInput("pdfurl", "PDF URL"))
),
row(
col(6, htmlOutput('pdfviewer')),
col(6, tags$iframe(style="height:600px; width:100%", src="https://localhost/www/R-intro.pdf"))
)
)
)
))
shinyApp(ui, server)
Hmm ok, against advice from the post
col(6, tags$iframe(style="height:600px; width:100%", src="R-intro.pdf")),
just referencing the file seems to work.

How open PDF file in the same window as R Shiny application works?

How to load PDF file in same window of R Shiny application?
Here is an example:
library(shiny)
ui <- fluidPage(
navbarPage("Demo",
tabPanel("Overview", fluidPage(fluidRow("Overview page"))),
tabPanel("PDF file", fluidRow(uiOutput("load_pdf_file")))))
server <- function(input, output) {
# 1. Load PDF file
output$load_pdf_file <- renderUI({
# 1.1. This loads pdf file in a 'new' window
browseURL("http://www.africau.edu/images/default/sample.pdf")
# 1.2. How to load pdf file in the 'same' window where R Shiny app works
# Expect to see pdf file on the page in 'PDF file' section
# ...
})
}
shinyApp(ui = ui, server = server)
The method that I know of, does not rely on serving up PDF's it uses the standard HTML methods one would use in a traditional webpage, with the shiny code js wrappers to place it in an iFrame.
With this method, in the tabPanel you set up an iFrame and give it some dimension ( I picked arbitrary ones) the decide if it scrolls or not, the use src to supply it with the path to your pdf file. The condition of course is that your PDF file is discoverable by some kind of a local path or URL to the outside world.
library(shiny)
ui <- fluidPage(
navbarPage("Demo",
tabPanel("Overview", fluidPage(fluidRow("Overview page"))),
tabPanel("PDF file",
tags$iframe(style="height:800px;
width:200%;
scrolling=no",
src="https://your-path/your-file.pdf"))))

display.mode = 'showcase' in shinyApp() call - no code shown

I would like to be able to use display.mode = 'showcase' in an app run with the shinyApp() function call. According to the docs I should be able to pass any arguments that go runApp() through the options argument. The showcase mode works (the window is split) but it does not show the code. What's interesting is that if I run runExample("01_hello") everything works fine. I'm using shiny 1.0.5.
Code:
library(shiny)
ui <- fluidPage(
titlePanel("Sample App"),
sidebarLayout(
sidebarPanel(
selectInput("data", label = "Data set",
choices = c("mtcars", "iris"))
),
mainPanel(
tableOutput("table")
)
)
)
server <- function(input, output) {
data <- reactive({
get(input$data, 'package:datasets')
})
output$table <- renderTable({
head(data())
})
}
shinyApp(ui, server, options = list(display.mode = 'showcase'))
Output:
I was having the same issue. I had the app.R file and created the DESCRIPTION file using notepad but couldn't deploy a shinyApp with the code. Then I copied the DESCRIPTION file from shiny\examples\01_hello and noticed this:
Turns out my file had a TXT extension, so Shiny wasn't reading it as a metadata file. Once I used the correct DESCRIPTION file (which you can edit using notepad), everything worked out fine.
This is more of an addendum to Gus_est's answer, since I had the same problem and wasn't able to get it run right from there.
Create a file inside the directory your app.R-file resides in, e.g. a txt-file. Write into the file what display mode is to be used using Debian Control file format. In our case it would look like that (Title is not necessary):
Title: My App
DisplayMode: Showcase
Then rename the file DESCRIPTION without providing a file ending. Ignore the warning.
When you run the app now, it will always be in display mode "showcase", you can override this only inside the runApp()-statement. So I find the documentation to be misleading.
Check your current working directory. This problem seems to occur, if the working directory is not set to the folder with the app code.

Resources