Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

embed_file

Embed a file, multiple files, or directory on an HTML page


Description

For a file, first encode it into base64 data (a character string). Then generate a hyperlink of the form <a href="base64 data" download="filename">Download filename</a>. The file can be downloaded when the link is clicked in modern web browsers. For a directory, it will be compressed as a zip archive first, and the zip file is passed to embed_file(). For multiple files, they are also compressed to a zip file first.

Usage

embed_file(path, name = basename(path), text = paste("Download", name), ...)

embed_dir(path, name = paste0(normalize_path(path), ".zip"), ...)

embed_files(path, name = with_ext(basename(path[1]), ".zip"), ...)

Arguments

path

Path to the file(s) or directory.

name

The default filename to use when downloading the file. Note that for embed_dir(), only the base name (of the zip filename) will be used.

text

The text for the hyperlink.

...

For embed_file(), additional arguments to be passed to htmltools::a() (e.g., class = 'foo'). For embed_dir() and embed_files(), arguments passed to embed_file().

Details

These functions can be called in R code chunks in R Markdown documents with HTML output formats. You may embed an arbitrary file or directory in the HTML output file, so that readers of the HTML page can download it from the browser. A common use case is to embed data files for readers to download.

Value

An HTML tag <a> with the appropriate attributes.

Note

Windows users may need to install Rtools to obtain the zip command to use embed_dir() and embed_files().

These functions require R packages mime and htmltools. If you have installed the rmarkdown package, these packages should be available, otherwise you need to install them separately.

Currently Internet Explorer does not support downloading embedded files (https://caniuse.com/#feat=download). Chrome has a 2MB limit on the file size.

Examples

logo = xfun:::R_logo()
link = xfun::embed_file(logo, text = "Download R logo")
link
if (interactive()) htmltools::browsable(link)

xfun

Miscellaneous Functions to Support Packages Maintained by 'Yihui Xie'

v0.22
MIT + file LICENSE
Authors
Yihui Xie [aut, cre, cph] (<https://orcid.org/0000-0003-0645-5666>), Wush Wu [ctb], Daijiang Li [ctb], Xianying Tan [ctb], Salim Brüggemann [ctb] (<https://orcid.org/0000-0002-5329-5987>), Christophe Dervieux [ctb]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.