Search code examples
htmlline-breaksdata-uriplaintext

How can line breaks be added to a data:text/plain URI?


My goal is to generate a text file with line breaks, using a data URI in HTML5's <a download> tag/attribute. Currently the line breaks seem to be ignored.

Below is an example of using HTML5 attribute of download, where the output is an HTML file with a link. When clicked, the link can be used to open or save a file.

Example with PHP to generate such a download link:

<?php
    //generate a string line with line breaks
    //i.e. using PHP:
    //where PHP_EOL is "The correct 'End Of Line' symbol for current platform"
    $content = "line" . PHP_EOL . "line"; 
?>

<a download="a.txt" href="data:text/plain;utf8,<?=$content?>">Download</a>

Despite the line-break in the string, currently my output is:

lineline

when expected output would be:

line
line

Examining the string using HEX, it does have the characters 0A 0D, which represent the CR and LF, so they are indeed there before the <a download> tag.

Is there a way to force line breaks to be seen in the downloaded file? If not, is this a limitation of HTML's download tag?


Solution

  • Use base 64 encode it.

    The following is "Hello\nWorld"

    <a download="foo.txt"
    href="data:text/plain;base64,aGVsbG8Kd29ybGQ=">
        Download
    </a>