
Shiny也提供了下載計(jì)算結(jié)果文件的特性,這能可以很容易地構(gòu)建報(bào)告系統(tǒng)。
要運(yùn)行下面的例子,鍵入:
> 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
,這個(gè)參數(shù)告訴瀏覽器保存時(shí)默認(rèn)的文件名,它可以是簡(jiǎn)單的字符串,也可以是返回字符串的函數(shù)(如上例)。
content
參數(shù)必須是包含一個(gè)參數(shù)的函數(shù),這個(gè)參數(shù)是臨時(shí)文件的文件名。content
函數(shù)的作用是往要下載的臨時(shí)文件里寫(xiě)內(nèi)容。
filename
和 content
參數(shù)可以使用反應(yīng)值或表達(dá)式(盡管在上面例子中的filename
,參數(shù)是實(shí)際的函數(shù),filename = paste(input$dataset, '.csv')
不會(huì)按你想的那樣運(yùn)行,因?yàn)楫?dāng)下載處理器定義時(shí),它只計(jì)算一次)。
一般來(lái)說(shuō),只有兩個(gè)參數(shù)你需要。有個(gè)可選參數(shù)contentType
,如果它是NA
或 NULL
,shiny會(huì)基于文件名猜測(cè)一個(gè)合適的值。如果你想改變這一行為,可以提供一個(gè)類(lèi)型的字符串(比如,"text/plain"
)








暫無(wú)數(shù)據(jù)