如何验证用户在 Shiny 应用程序中上传的文件的文件类型?

How to validate the file type of a file uploaded by the user in a Shiny app?

我正在尝试创建一个闪亮的应用程序(使用 R Studio)。

我想使用 fileInput 小部件(名为 ffile)从用户读取 xlsx 或 xls 文件。但是,我需要它来确保它是正确的文件类型,否则其余代码将无法运行。我阅读了 validate() 和 need() 函数。所以我这样做了:

data<-reactive({ 
infile = input$ffile 
if (is.null(infile)) 
return(NULL)
ext<-c('application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

o<-is.element(infile$type,ext)
validate(need(o,'Wrong ext. Select .xls, .xlsx or .csv'))
file<-read.xlsx(infile$datapath, 1)
return(file) })

我尝试加载 .docx 文档,它被成功阻止,并按要求显示警告消息。但是,当我尝试加载正确的 .xlsx 文件时,它仍会显示警告消息而不是实际接受它。我不知道我是否使用了 validate/need 不正确,或者我对 MIME 不太了解。我们将不胜感激。

您可以使用 accept 参数直接在 ui.RfileInput 对象中设置接受的 MIME:

fileInput('file1', 'Choose CSV File',
                accept=c('application/vnd.ms-excel',
                         'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                         '.xls',
                         '.xlsx'))

这只会让用户 select excel 从文件浏览器 window 打开的文件。

在您的 server.R 中,您可以直接从文件中获取数据而无需验证。