我正在构建一个 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/