文件编码为直接在href属性中进行下载的Base64编码字符串 [英] File encoded as Base64 encoded string directly in href attribute for download

查看:451
本文介绍了文件编码为直接在href属性中进行下载的Base64编码字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个文件,例如编码为Base64字符串的MS Word文档,是否有办法通过将字符串放在A标签的href属性中以及一些MIME信息来使其可用?



理想情况下,我想要做类似...



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

[... ]是字符串的其余部分,为了可读性而被截断。



我只需要知道这是否值得追求,或者如果我吠叫错误的树。感谢。

解决方案

我设法通过以下方法完成我想要完成的任务:

1)我使用.htaccess重写url,如下所示:

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

这样我的链接可以指向什么似乎是一个真正的文件,而不是.php文件,所以 /downloads/your_file.doc 变成 /file.php?filename=your_file。 doc



<2>在 file.php中

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

请注意 Content-type:application / msword 仅适用于 .doc 文件,并且您希望将其替换为相应文件的适当MIME类型,或者通过将其替换为动态一个变量,如果优先。



我发现这个主题对于找到一个可行的解决方案非常有用。


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.

解决方案

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.

这篇关于文件编码为直接在href属性中进行下载的Base64编码字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆