我正在尝试创建一个 Shiny 的应用程序(使用 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.R
的 fileInput
对象中设置接受的 MIME:
fileInput('file1', 'Choose CSV File',
accept=c('application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.xls',
'.xlsx'))
这只会让用户从打开的文件浏览器窗口中选择 excel 文件。
在您的 server.R
中,您可以直接从文件中获取数据而无需验证。
关于r - 如何验证用户在 Shiny 应用程序中上传的文件的文件类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29201155/