Marc
Marc

Reputation: 746

File encoded as Base64 encoded string directly in href attribute for download

If I have a file, for example MS Word document encoded as a Base64 string, is there a way to make it available as a download by putting the string in the href attribute of an A tag along with some MIME info?

Ideally, I would like to do something like...

<a href="data:Application/base64,UEsDBBQABgAIAAAAIQDfpNJsWgEAAC[...]"></a>

[...] being the rest of the string, truncated for readability.

I just need to know if this is worth pursuing or if I'm barking up the wrong tree. Thanks.

Upvotes: 2

Views: 4021

Answers (1)

Marc
Marc

Reputation: 746

I managed to accomplish what I wanted to do via the following method:

1) I used .htaccess to rewrite the url as follows:

RewriteRule ^downloads/(.*)$ file.php?filename=$1 [L,NC]

That way my link can point to what appears to be a real file rather than a .php file, so /downloads/your_file.doc becomes /file.php?filename=your_file.doc.

2) Within file.php I set the headers as follows:

$filename = $_GET['filename'];
header("Content-type: application/msword"); 
header("Content-Disposition: attachment; filename=$filename"); 
echo base64_decode($your_base64_data);

Please note that Content-type: application/msword is only appropriate for .doc files, and you will want to replace this with the appropriate mime type for the file in question, or even make it dynamic by replacing it with a variable if preferred.

I found this thread very useful in coming to a working solution.

Upvotes: 1

Related Questions