Shiny可以将用户的数据上传到到你的应用程序里。用户可以通过浏览器进行数据的上传,并且服务器端可以访问这些数据。 一般情况下,shiny上传的数据有文件大小有限制,一般不能超过5M。可以通过shiny.maxRequestSize选项来修改这个限制。例如,在server.R的最前面加上 options(shiny.maxRequestSize=30*1024^2),可以把文件大小限制提高到30MB。
文件的上传
运行下面这个上传文件的例子:
代码语言:javascript复制library(shiny)
runExample("09_upload")
具体代码为
代码语言:javascript复制#UI
ui<-shinyUI(pageWithSidebar(
headerPanel("CSV Viewer"),
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv', 'text/comma-separated-values,text/plain')),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='t'),
'Comma'),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'Double Quote')
),
mainPanel(
tableOutput('contents')
)
))
代码语言:javascript复制#server.R
server<-shinyServer(function(input, output) {
output$contents <- renderTable({
# input$file1 will be NULL initially. After the user selects and uploads a
# file, it will be a data frame with 'name', 'size', 'type', and 'datapath'
# columns. The 'datapath' column will contain the local filenames where the
# data can be found.
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.csv(inFile$datapath, header=input$header, sep=input$sep, quote=input$quote)
})
})
shinyApp(ui,server)
文件上传函数为ui文件中的 fileInput
,访问上传的数据也跟访问其他类型的输入相类似:用input$inputId来引用。accept
提示用户上传文件类型。
文件的下载
运行下载示例文件
代码语言:javascript复制library(shiny)
runExample("10_download")
代码语言:javascript复制library(shiny)
# Define UI for data download app ----
ui <- fluidPage(
# App title ----
titlePanel("Downloading Data"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Choose dataset ----
selectInput("dataset", "Choose a dataset:",
choices = c("rock", "pressure", "cars")),
# Button
downloadButton("downloadData", "Download")
),
# Main panel for displaying outputs ----
mainPanel(
tableOutput("table")
)
)
)
代码语言:javascript复制# Define server logic to display and download selected file ----
server <- function(input, output) {
# Reactive value for selected dataset ----
datasetInput <- reactive({
switch(input$dataset,
"rock" = rock,
"pressure" = pressure,
"cars" = cars)
})
# Table of selected dataset ----
output$table <- renderTable({
datasetInput()
})
# Downloadable csv of selected dataset ----
output$downloadData <- downloadHandler(
filename = function() {
paste(input$dataset, ".csv", sep = "")
},
content = function(file) {
write.csv(datasetInput(), file, row.names = FALSE)
}
)
}
代码语言:javascript复制# Create Shiny app ----
shinyApp(ui, server)
下载的功能通过ui里的downloadButton
或 downloadLink
。sever里的downloadHandler
函数实现.