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

标签 r shiny rstudio shiny-server

我正在尝试创建一个 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.RfileInput 对象中设置接受的 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/

相关文章:

r - plotly 生存图

r - RStudio 中的编织错误 : pandoc conversion failed with error 23. Markdown 不支持扩展 ascii_identifiers

r - 有没有办法将 csv 数据粘贴到 R 而不是从文件中读取?

r - 如何在 Shiny 页面内呈现 scatter3d 而不是弹出窗口

根据R中消息框的响应运行程序

R Shiny 动态框高度

r - 在 RStudio 中执行多行的快捷方式

r - 分析没有日期的时间序列

R - 作为数字矩阵

r - R中的离散化