I'm trying to create a Shiny App (using R Studio).
I want to use a fileInput widget (named ffile) to read an xlsx or xls file from the user. However, I need it to make sure that it's the correct file type, otherwise the rest of the code will not work. I read about the validate() and need() functions. So I did it like this:
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) })
I tried loading a .docx document and it was successfully blocked and the warning message was displayed as desired. However, when I try to load a correct .xlsx file it would still show the warning message instead of actually accepting it. I do not know if I'm using the validate/need incorrectly or there is something about MIMEs that I don't quite understand. Help would be appreaciated.
You can set the accepted MIME directly in the fileInput
object in your ui.R
using the accept
argument:
fileInput('file1', 'Choose CSV File',
accept=c('application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.xls',
'.xlsx'))
This will only let the user select excel files from the file browser window that opens.
In your server.R
, you can then just get the data from the file without validating.