R Shiny - downloading a csv to the working directory

白昼怎懂夜的黑 提交于 2021-01-27 13:04:48

问题


I’ve got a Shiny app in which I’d like to accomplish the following:

1) User presses a button

2) A data frame gets exported to a .csv, saved in either the working directory (with server.R and ui.R), or ideally one level down.

I want this to happen automatically, because eventually I’m going to connect it with a checkboxGroupboxInput to loop through the data and produce a set of filtered .csv.

Here is the closest I can currently get, with fileToDownload representing my data frame:

ui.R:

downloadButton("rptDownload", "Download Report"),

server.R:

output$rptDownload <- downloadHandler(
   filename = function() {
     paste(getwd(), '/rpt/test.csv',sep = '')
   },
   content = function(con) {
     write.csv(fileToDownload, file = file.path(con))
   }
 )

When I run this from a Chrome browser, it downloads to a .csv, but it gets named with what I want to be the file path as part of the name: C--Work-Project_A-Shiny_DB-rpt-test.csv. It regards the getwd() and /rpt/ as part of the name instead of the file path. It gets downloaded to my Downloads folder, not the current working directory.

Any suggestions on how to improve my code?

Note that I have tried incorporating some suggestions from other threads. Among others:

Shiny (R): Download selection in selectInput to local machine

Automatic multi-file download in R-Shiny

https://groups.google.com/forum/#!topic/shiny-discuss/MaN4-ia6wfk

But these seem to be moving me further away from accomplishing what I'm trying to do. Thanks for any assistance.


回答1:


I think what you want is for the user to click a button and have shiny save the data to some folder which you specify. Is this correct?

If that's what you want, then create a button which, when clicked by the user, will just write.csv(<DF-to-write>, <filename-to-use>) or something along those lines.

No need to use downloadHandler. The downloadHandler function is specific to exporting the data: The user clicks on this button and your app exports the data for them. The reason the data shows up in your Download folder when you use it this way is because you've set up your browser to store all downloaded files to your Download directory.

If you want, you can have one button for SaveSelectedData and another button for DownloadSavedData.

  • SaveSelectedData will write.csv the df's of interest to your specified folder.

  • DownloadSavedData will export the data out to your user (you can't specify where it will get downloaded to on your user's system though -- that's dependent on their browser settings).

Also keep in mind that when running on the server, you'll need to make sure that Shiny has permissions to write to the folder you want it to save files to.



来源:https://stackoverflow.com/questions/34865635/r-shiny-downloading-a-csv-to-the-working-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!