2018-10-26
閱讀量:
1950
用R搭建的shiny應(yīng)用程序怎么上傳文件
有時(shí)你希望用戶能上傳數(shù)據(jù)到你的應(yīng)用程序里。shiny使得用戶可以很容易地用瀏覽器上傳數(shù)據(jù),然后服務(wù)端的邏輯可以訪問這些數(shù)據(jù)。
重要注解:
- 這一特性不支持IE9或更早版本(shiny server也同樣不支持它們)
- 默認(rèn)情況下,shiny上傳的每個(gè)文件最大不能超過5MB。你可以通過
shiny.maxRequestSize
選項(xiàng)來修改這個(gè)限制。例如,在server.R
的最前面加上options(shiny.maxRequestSize=30*1024^2)
,可以把文件大小限制提高到30MB。
要運(yùn)行這個(gè)例子,可鍵入:
> library(shiny)
> runExample("09_upload")
文件上傳控件是ui.R
文件中的 fileInput
來創(chuàng)建的,訪問上傳的數(shù)據(jù)也跟訪問其他類型的輸入相類似:用input$inputId
來引用。fileInput
函數(shù)的multiple
參數(shù)取TRUE
可以允許用戶選擇多個(gè)文件,而accept
參數(shù)可以提示用戶應(yīng)用程序希望接收什么樣的文件類型。
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')
)
))
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)
})
})
上面這個(gè)接收了一個(gè)文件,然后用read.csv
函數(shù)讀取這個(gè)csv文件,最后用表格來展示所有的數(shù)據(jù)。正如server.R
的注釋展示的那樣,inFile
要么是NULL
,要么是包含上傳文件信息的數(shù)據(jù)框,每一行對(duì)應(yīng)的一個(gè)文件。在本例中,fileInput
沒有multiple
參數(shù),這樣它就只有一行。






評(píng)論(0)


暫無數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
0條評(píng)論
0條評(píng)論