我希望在我的闪亮应用程序中有一个功能,当有人上传不是.csv格式的文件时,他们会收到警告,当他们以.csv格式上传时,会打印该表。这是我的UI代码
shinyUI(
tabPanel("File Upload",
h4("File Upload"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)
)
),
mainPanel(
tableOutput('upload'),
h1(textOutput("warning1"))
)
)
)
)
和我的服务器代码
shinyServer(function(input, output) {
output$upload <- renderTable({
#assign uploaded file to a variable
File <- input$file1
#catches null exception
if (is.null(File))
return(NULL)
read.csv(File$datapath)
})
output$warning1 <- renderPrint({
upload<- input$file1
if (is.null(upload))
return(NULL)
if (upload$type != c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)
)
return ("Wrong File Format try again!")
})
}
答案 0 :(得分:0)
您真正需要的是validate
声明。此外,您需要使用%in%
函数来检查值是否在向量中,只是FYI。以下是一个更简单的警告/错误实现。它使用file_ext
包中的tools
函数。
library(shiny)
library(tools)
runApp(
list(
ui = tabPanel("File Upload",
h4("File Upload"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'csv',
'tsv'
)
)
),
mainPanel(
tableOutput('upload')
)
)
),
server = function(input, output){
output$upload <- renderTable({
#assign uploaded file to a variable
File <- input$file1
#catches null exception
if (is.null(File))
return(NULL)
validate(
need(file_ext(File$name) %in% c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'csv',
'tsv'
), "Wrong File Format try again!"))
read.csv(File$datapath)
})
}
))