【问题标题】:How to validate the file type of a file uploaded by the user in a Shiny app?如何验证用户在 Shiny 应用中上传的文件的文件类型?
【发布时间】:2015-05-25 21:44:58
【问题描述】:

我正在尝试创建一个闪亮的应用程序(使用 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 文件时,它仍然会显示警告消息,而不是实际接受它。我不知道我是否错误地使用了验证/需要,或者我不太了解 MIME 的某些内容。将不胜感激。

【问题讨论】:

    标签: r shiny rstudio shiny-server


    【解决方案1】:

    您可以使用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 中,您可以直接从文件中获取数据而无需验证。

    【讨论】:

    • 我试过了,ui.R 中的小部件代码如下所示:` fileInput("ffile", label = h4("Choose file"), accept=c('application/vnd .ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','.xls', '.xlsx'))` 但是当我运行它时,它完全忽略了accept 参数。默认情况下,它仍然允许我选择任何类型的文件。
    • 这仅适用于网络浏览器,但不适用于 Rstudio 查看器。
    • 我已经验证了 wikiselev 的评论,它在网络浏览器中完美运行。
    猜你喜欢
    • 2010-09-09
    • 2013-12-14
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2017-11-08
    相关资源
    最近更新 更多