javascript - 在将图像上传到 Shiny 之前渲染图像

标签 javascript r shiny shinyjs

我正在构建一个 Shiny 的应用程序,允许用户将图像上传到服务器。我想在屏幕上显示图像,而不必先上传图像,然后再获取渲染的输出。这可能吗?

这是我现在的代码。您可以选择上传的图像文件。收到图像后,图像将在服务器端从文件中呈现。我想避免往返。

用户界面

fluidPage(
    titlePanel("File upload"),
    sidebarLayout(
        sidebarPanel(
            fileInput("img", "Choose image file",
                accept=c("image/jpeg", "image/x-windows-bmp"))
        ),
        mainPanel(
            imageOutput("picture", width="500px", height="500px")
        )
    )
)

服务器

function(input, output, session)
{
    output$picture <- renderImage({
        imgFile <- input$img
        if(is.null(imgFile))
            return(list(src=""))
        list(src=imgFile$datapath, alt=imgFile$name, contentType=imgFile$type)
    }, deleteFile=FALSE)

    # do more stuff with the file
}

最佳答案

您可以使用包 shinyjs 从 HTML 5 read here 调用 FileReader

library(shinyjs)
shinyApp(ui = fluidPage(
  useShinyjs(),
  titlePanel("File upload"),
  sidebarLayout(
    sidebarPanel(
      fileInput("img", "Choose image file",
                accept=c("image/jpeg", "image/x-windows-bmp")),
      HTML('<output id="list"></output>')
    ),
    mainPanel(
      imageOutput("picture", width="500px", height="500px")
    )
  )), 
server = function(input, output, session){ 
  shinyjs::runjs("

  function handleFileSelect(evt) {
   var files = evt.target.files; // FileList object
   // Loop through the FileList and render image files as thumbnails.
   for (var i = 0, f; f = files[i]; i++) {

   // Only process image files.
   if (!f.type.match('image.*')) {
   continue;
   }

   var reader = new FileReader();

   // Closure to capture the file information.
   reader.onload = (function(theFile) {
   return function(e) {
   // Render thumbnail.
   var span = document.createElement('span');
   span.innerHTML = ['<img class=\"thumb\" src=\"', e.target.result,
   '\" title=\"', escape(theFile.name), '\"/>'].join('');
   document.getElementById('list').insertBefore(span, null);
   };
   })(f);

   // Read in the image file as a data URL.
   reader.readAsDataURL(f);
   }
   }
   document.getElementById('img').addEventListener('change', handleFileSelect, false);")

  output$picture <- renderImage({
    imgFile <- input$img
    if(is.null(imgFile))
      return(list(src=""))
    list(src=imgFile$datapath, alt=imgFile$name, contentType=imgFile$type)
    }, deleteFile=FALSE)
})

关于javascript - 在将图像上传到 Shiny 之前渲染图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42120466/

相关文章:

javascript - 如果在页面加载时勾选复选框并单击该复选框,则禁用输入

javascript - 为什么我的 Javascript switch 语句不起作用?

r - R 中的方法根据特定参数的存在进行调度

r - 面积图显示较大的值低于较小的值

r - 从多串字母和数字中减去1个字母和数字

javascript - JS Regex .replace,我缺少什么?

javascript - 我可以使用 unpkg 或 browserify 在前端项目中包含单个 NPM 包吗?

r - 在 R 中使用带有 Shiny 的 flexdashboard 使 DT (DataTable) 响应

html - 将 Shiny 的应用程序嵌入到 Rmarkdown html 文档中

r - 如何在 R studio 中分层比较两个 ggplot(换句话说,有两个图相互重叠并通过我的输入进行比较)?