2018-10-26
閱讀量:
1896
在R里構(gòu)建的shiny應用程序如何下載數(shù)據(jù)

Shiny也提供了下載計算結(jié)果文件的特性,這能可以很容易地構(gòu)建報告系統(tǒng)。
要運行下面的例子,鍵入:
> library(shiny)
> runExample("10_download")
要定義文件下載的功能,在服務(wù)端用downloadHandler
使用函數(shù),在UI端使用downloadButton
或 downloadLink
。
shinyUI(pageWithSidebar(
headerPanel('Download Example'),
sidebarPanel(
selectInput("dataset",
"Choose a dataset:",
choices
=
c("rock",
"pressure",
"cars")),
downloadButton('downloadData',
'Download')
),
mainPanel(
tableOutput('table')
)
))
shinyServer(function(input,
output)
{
datasetInput
<-
reactive({
switch(input$dataset,
"rock"
=
rock,
"pressure"
=
pressure,
"cars"
=
cars)
})
output$table
<-
renderTable({
datasetInput()
})
output$downloadData
<-
downloadHandler(
filename
=
function()
{
paste(input$dataset,
'.csv',
sep='')
},
content
=
function(file)
{
write.csv(datasetInput(),
file)
}
)
})
正如你看的那樣,downloadHandler
接收參數(shù)filename
,這個參數(shù)告訴瀏覽器保存時默認的文件名,它可以是簡單的字符串,也可以是返回字符串的函數(shù)(如上例)。
content
參數(shù)必須是包含一個參數(shù)的函數(shù),這個參數(shù)是臨時文件的文件名。content
函數(shù)的作用是往要下載的臨時文件里寫內(nèi)容。
filename
和 content
參數(shù)可以使用反應值或表達式(盡管在上面例子中的filename
,參數(shù)是實際的函數(shù),filename = paste(input$dataset, '.csv')
不會按你想的那樣運行,因為當下載處理器定義時,它只計算一次)。
一般來說,只有兩個參數(shù)你需要。有個可選參數(shù)contentType
,如果它是NA
或 NULL
,shiny會基于文件名猜測一個合適的值。如果你想改變這一行為,可以提供一個類型的字符串(比如,"text/plain"
)






評論(0)


暫無數(shù)據(jù)
推薦帖子
0條評論
0條評論
0條評論