Rshiny Pass list of files to Javascript downloader

二次信任 提交于 2020-07-22 05:58:09

问题


I'm on the home stretch thanks to Stephane Laurent!

I have an Rshiny app that generates a timeline based on a user selecting rows from a data table. The user can then download a zip file containing the table, the timeline, and hopefully the files associated with the rows selected in the table.

I believe I need to pass the filenames from my Rshiny table to JS in order for JS to add the file URL's to a function for JSZip. The files are stored in my app directory under the www folder. so "https://server.me/myapp/Room.pdf" is how navigate to a file. (I've only done something like this with php in the past.)

So in the code below, if a user clicked on the Big Room and Red Rover, then generated a timeline, and then downloaded. They would get a zip file containing timeline.png, timeline.csv, Room.pdf, and Activity.docx

Bonus I would also like the ability to add specific files to all downloads. (I imagine that's fairly simple as I can just point it to the specific url "https://server.me/myapp/Thanks_for_visiting.pdf" without needing Rshiny to do anything.)

Can I pass multiple "things: with session$sendCustomMessage ? Or do it twice? something like:

file_list <- as.data.frame(row_data$file_name)
    
    output$tbl2 <- DT::renderDataTable({
      file_list})

session$sendCustomMessage("file_list",
                              fromJSON(toJSON(input$file_list), simplifyDataFrame = FALSE))

CODE

library(shiny)
library(timevis)
library(lubridate)
library(dplyr)
library(jsonlite)

starthour <- 8
today <- as.character(Sys.Date())
todayzero <- paste(today, "00:00:00")
todayAM <- paste(today, "07:00:00")
todayPM <- paste(today, "18:00:00")

items <- data.frame(
  category = c("Room", "IceBreaker", "Activity", "Break"),
  group = c(1, 2, 3, 4),
  className   = c ("red_point", "blue_point", "green_point", "purple_point"),
  content = c("Big Room", "Introductions", "Red Rover", "Lunch"),
  length = c(480, 60, 120, 90),
  file_name = c("Room.pdf", "NA", "Activity.docx", "Break.txt")
)

groups <- data.frame(id = items$group, content = items$category)

data <- items %>% mutate(
  id = 1:4,
  start = as.POSIXct(todayzero) + hours(starthour),
  end   = as.POSIXct(todayzero) + hours(starthour) + minutes(items$length)
)

js <- "
function downloadZIP(jsontable){
var csv = Papa.unparse(jsontable);
domtoimage.toPng(document.getElementById('appts'), {bgcolor: 'white'})
.then(function (dataUrl) {
var zip = new JSZip();
var idx = dataUrl.indexOf('base64,') + 'base64,'.length;
var content = dataUrl.substring(idx);
zip.file('timeline.png', content, {base64: true})
.file('timeline.csv', btoa(csv), {base64: true});
zip.generateAsync({type:'base64'}).then(function (b64) {
var link = document.createElement('a');
link.download = 'mytimeline.zip';
link.href = 'data:application/zip;base64,' + b64;
link.click();
});
});
}
$(document).on('shiny:connected', function(){
Shiny.addCustomMessageHandler('download', downloadZIP);
});"

ui <- fluidPage(
  tags$head(
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/jszip/3.5.0/jszip.min.js"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.2.0/papaparse.min.js"),
    tags$script(HTML(js)),
    tags$style(
      HTML(
        "
        .red_point  { border-color: red; border-width: 2px;   }
        .blue_point { border-color: blue; border-width: 2px;  }
        .green_point  { border-color: green; border-width: 2px;   }
        .purple_point { border-color: purple; border-width: 2px;  }
        "
      )
      )
      ),
  DT::dataTableOutput("tbl1"),
  conditionalPanel(
    condition = "typeof input.tbl1_rows_selected  !== 'undefined' && input.tbl1_rows_selected.length > 1",
    actionButton(class = "btn-success",
                 "button2",
                 "GENERATE TIMELINE")
  ),
  
  conditionalPanel(
    condition = "input.button2 > 0",
    
    timevisOutput("appts"),
    actionButton("download", "Download timeline", class = "btn-success")
  )
      )

server <- function(input, output, session) {
  output$tbl1 <- DT::renderDataTable({
    data
  },
  caption = 'Select desired options and scroll down to continue.',
  selection = 'multiple',
  class = "display nowrap compact",
  extensions = 'Scroller',
  options = list(
    dom = 'Bfrtip',
    paging = FALSE,
    columnDefs = list(list(visible = FALSE))
  ))
  
  
  observeEvent(input$button2, {
    row_data <- data[input$tbl1_rows_selected, ]
    
    output$appts <- renderTimevis(timevis(
      data = row_data,
      groups = groups,
      fit = TRUE,
      options = list(
        editable = TRUE,
        multiselect = TRUE,
        align = "center",
        stack = TRUE,
        start = todayAM,
        end = todayPM,
        showCurrentTime = FALSE,
        showMajorLabels = FALSE
      )
    ))
  })
  
  observeEvent(input$download, {
    session$sendCustomMessage("download",
                              fromJSON(toJSON(input$appts_data), simplifyDataFrame = FALSE))
  })
  
}

shinyApp(ui, server)

回答1:


library(base64enc)

js <- "
function downloadZIP(x){
  var csv = Papa.unparse(x.table);
  var URIs = x.URIs;
  domtoimage.toPng(document.getElementById('appts'), {bgcolor: 'white'})
    .then(function (dataUrl) {
      var zip = new JSZip();
      var idx = dataUrl.indexOf('base64,') + 'base64,'.length;
      var content = dataUrl.substring(idx);
      zip.file('timeline.png', content, {base64: true})
       .file('timeline.csv', btoa(csv), {base64: true});
      for(let i=0; i < URIs.length; ++i){
        zip.file(URIs[i].filename, URIs[i].uri, {base64: true});
      }
      zip.generateAsync({type:'base64'}).then(function (b64) {
        var link = document.createElement('a');
        link.download = 'mytimeline.zip';
        link.href = 'data:application/zip;base64,' + b64;
        link.click();
      });
    });
}
$(document).on('shiny:connected', function(){
  Shiny.addCustomMessageHandler('download', downloadZIP);
});"

  observeEvent(input$download, {
    filenames <- data[input$tbl1_rows_selected, "file_name"]
    files <- file.path(".", "www", filenames)
    URIs <- lapply(seq_along(files), function(i){
      URI <- dataURI(file = files[i])
      list(filename = filenames[i], uri = substr(URI, 14, nchar(URI)))
    })
    table <- fromJSON(toJSON(input$appts_data), simplifyDataFrame = FALSE)
    session$sendCustomMessage(
      "download",
      list(table = table, URIs = URIs)
    )
  })


来源:https://stackoverflow.com/questions/62797460/rshiny-pass-list-of-files-to-javascript-downloader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!