首页 > 解决方案 > 在 R Shiny 中下载压缩的 PNG

问题描述

我正在编写一个 R Shiny 应用程序(我想在 Shiny 服务器上托管),它将从 API 下载 PNG,在屏幕上显示它们,然后允许用户将它们下载为 .zip 文件。对于我的生活,我无法弄清楚如何压缩 PNG。我设法让应用程序在本地运行时提示下载 PNG。代码如下。我很感激任何帮助。

ui.R:

library(shiny)
    shinyUI(fluidPage(
    
        titlePanel("Modified Script"),
    
        sidebarLayout(
            inputPanel(
                textInput("URL","TEXT", ""),
                submitButton("Update View", icon("refresh"))),
    
            mainPanel(
                htmlOutput("images"),
                
                    titlePanel('Downloading Data'),
                    sidebarLayout(
                        sidebarPanel(
                            downloadButton('imgs', 'Download')
                        ),
                        mainPanel()
                    )
                )
            
                )
        )
    )

服务器.R:

library(shiny)
library(httr)
library(jsonlite)

shinyServer(function(input, output, session) {

 imgFiles <- reactiveValues(mat=NULL)
        
 output$images <- renderText({
      dURL = input$URL
      dId = gsub("\\?.*","",gsub('.*/', '', dURL))
      dJson = paste0('[api Location]',dID,'/export/json')
        
        tech = GET(dJSON)
        data = fromJSON(rawToChar(tech$content))
        
        nImage = data$image
        nName = data$name
            
       
        withProgress(message = 'Making plot', value = 0, {
          # Number of times we'll go through the loop
        n <- length(nImage)
        
        count<-0
        images1<-NULL
        images2<-NULL
        destFile<-NULL
        for (x in nImage){
          destFile = paste0(nName[(count+1)],'.png')
          images = c('<img src="',x,'" width=10% height=10%>',images)

          Sys.sleep(.69)
          count = count+1
          
          incProgress(1/n, detail = paste("Doing part", x))
         
          imgFiles$html <- image1
          imgFiles$imgs <- nImage
          imgFiles$names<- nName
          
           }     
        })
        print(imgFiles$html)
        
       })
      
 output$imgs<-renderText({
   
   as.vector(imgFiles$imgs)
 })
})

标签: rshiny

解决方案


我想出了一种通过使用tar而不是zip. 我打算再玩一些,但这似乎适用于 Shiny Server。

 output$imgs <- downloadHandler(
       filename = "DownloadPNGs.tar",
       
       content = function(file){
        
          tmpdir <- tempdir()
          setwd(tempdir())
          count<-0
          for (i in imgFiles$imgs){
            path <-paste0(imgFiles$names[count+1],".png")
            download.file(i,path,mode="wb")
            Sys.sleep(.69)
            count=count+1
       }
        tar(tarfile = file,files=tmpdir)
    }
     ) 

推荐阅读