【发布时间】:2017-11-07 16:58:28
【问题描述】:
我设计了一个使用闪亮的工具,要求用户上传通过单选按钮设计的 csv 或 xlsx 文件。现在有四个条件
- 他选择了csv,上传了一个csv文件,没错
- 选择 xlsx 并上传 xlsx 文件,同样正确
- 选择csv并上传xlsx文件,这是不正确的
- 选择 xlsx 并上传 csv 文件也不正确
现在对于第 3 点和第 4 点,我检查是否有任何不匹配,如果是则警告用户重新加载正确的文件类型。但是,第 4 点没有被检测到,并且工具通过其自身的错误。
用户界面代码
library(shiny)
library(xlsx)
library(tools)
shinyUI(fluidPage(
titlePanel("fileinput"),
sidebarLayout(
sidebarPanel(
radioButtons("filetype", "Select file type",choices=c("csv file","xlsx file")),
fileInput("file1","upload",accept = c("text/csv","text/comma-separated-values,text/plain",".csv",".xlsx",".xls"))
),
mainPanel(
uiOutput("Image_Data")
)
)
)
)
服务器代码
shinyServer(function(input, output) {
# loading data
data <- reactive({
if(input$filetype=="xlsx file"){
inFile <- input$file1
if (is.null(inFile))
return(NULL)
a<-read.xlsx(inFile$datapath, sheetIndex=1,header =TRUE)
as.data.frame(a)
}else{
inFile <- input$file1
if (is.null(inFile))
return(NULL)
a<-read.csv(inFile$datapath,header =TRUE,stringsAsFactors = TRUE)
as.data.frame(a)
}})
# info of the file
output$about_file<-renderTable({
input$file1})
# to display data
output$display <- renderDataTable({
data()})
# passing to UI finally
output$Image_Data<-renderUI({
if(is.null(data())){
h1("forecasting tool")
}
else if(input$filetype=="csv file" & input$file1$type != "text/csv"){
sprintf("reload correct file type")}
else if(input$filetype=="xlsx file" & input$file1$type !=
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
sprintf("reload correct file type")}
else if(input$filetype=="xlsx file" & input$file1$type !=
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
sprintf("reload correct file type")
}else{
tabsetPanel(tabPanel("DATA",dataTableOutput("display")),
tabPanel("aboufile", tableOutput("about_file")))
}})})
我确实安装了 java 64 位,这是在 r 中使用 excel 文件所必需的。
【问题讨论】:
-
将文件名作为文本字符串引入并检查扩展名,然后根据扩展名加载不是更容易吗?