Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 Encoding for CSV with R Markdown

Tags:

r

Base64 encoding of images is a really cool little feature in R Studio Markdown that creates all in one HTML pages that are easy to distribute or share. No need to worry about having the image as a seperate file. The browser knows what to do with it.

I'd like to extend this functionality to encoding CSV files as well. Looking at how they are doing it now, it looks like they are passing the information to .Call and using C/C++ to encode the file information.

From (line 177, and 192) : https://github.com/rstudio/markdown/blob/master/R/renderMarkdown.R

.b64EncodeFile <- function(inFile)
{
   fileSize <- file.info(inFile)$size

   if (fileSize > 0){
      paste( "data:", .mimeType(inFile),";base64,",
         .Call(rmd_b64encode_data,readBin(inFile,'raw',n=fileSize)),
         sep='')
   } else {
      warning(inFile,'is empty!')
      inFile
   }
}


.b64EncodeImages <- function(html)
{
   reg <- "<\\s*[Ii][Mm][Gg]\\s+[Ss][Rr][Cc]\\s*=\\s*[\"']([^\"']+)[\"']"
   m <- gregexpr(reg,html,perl=TRUE)
   if (m[[1]][1] != -1)
   {
      .b64EncodeImgSrc <- function(imgSrc)
      {
         inFile <- sub(reg,"\\1",imgSrc)
         if (length(inFile) && file.exists(inFile))
            imgSrc <- sub(inFile,.b64EncodeFile(inFile),imgSrc,fixed=TRUE)

         imgSrc
      }
      regmatches(html,m) <- list(unlist(lapply(regmatches(html,m)[[1]],.b64EncodeImgSrc)))
   }

   html
}

Now, how do I accomplish the same thing, with a CSV file? Importantly, how do I get the browser to understand it.

like image 310
Brandon Bertelsen Avatar asked Sep 01 '25 22:09

Brandon Bertelsen


1 Answers

If I read your intentions right, if you make an A element with the encoded data in the HREF attribute, then clicking on the link will get the file. Just tested this with an encoded image block I had lying around:

<a href="data:image/jpeg;base64,[blah blah blah]">Click Me</a>

So as long as you set the mime type (text/something?) all you need do is construct that element and stick it in your HTML file. User clicks link, file download starts, from its embedded base64 encoding. Sorted. Complete example with a missing mime-type which just lets the browser read it:

<html>
<head>
</head>
<body>
<h1>Test</h1>
<a href="data:;base64,aWQsbmFtZSxhZ2UKMSwiRnJlZCBGb28iLDk5CjIsIkpvZSBCbG9nZ3MiLDIyCg==">click me</a>
</body>
</html>

Where that data string has come from:

> markdown:::.b64EncodeFile("test.csv")
[1] "data:;base64,aWQsbmFtZSxhZ2UKMSwiRnJlZCBGb28iLDk5CjIsIkpvZSBCbG9nZ3MiLDIyCg=="
like image 176
Spacedman Avatar answered Sep 03 '25 14:09

Spacedman