简体   繁体   English

下载以base64编码的文件时pdf文件已损坏

[英]pdf file is corrupted when a file encoded in base64 is downloaded

I try to download a pdf file that has been previously encoded using base 64. 我尝试下载以前使用base 64编码的pdf文件。

I try to download it from an anchor tag, as follows 我尝试从锚标记下载它,如下所示

<a href="data:application/pdf;base64,JVBERi0xLjUKJbXtrvsKMyAwIG9..." download="file.pdf">Download</a>;

The file is downloaded but when I try to open it I get a message that the file has damage or is corrupted. 该文件已下载,但是当我尝试打开该文件时,我收到一条消息,指出该文件已损坏或已损坏。

Interestingly, if I change href to an encode image data, the file is downloaded and opened as expected. 有趣的是,如果我将href更改为编码图像数据,则文件将按预期下载并打开。

I found this example http://jsfiddle.net/filixix/0816jdfq/ and I see that is changed from data:application/pdf;base64, to data:application/octet-stream;base64 , I tried but I am getting the same result. 我找到了这个示例http://jsfiddle.net/filixix/0816jdfq/ ,我发现它已从data:application/pdf;base64,更改为data:application/octet-stream;base64 ,我尝试了但我得到了相同的结果结果。

Update 更新资料

I am encode the pdf file as follows 我将pdf文件编码如下

const element = document.querySelector('#file'); // input type file

element.addEventListener('change', handleChange);

function handleChange() {
    const file = this.files[0];
    const fileReader = new FileReader();

    fileReader.onload = function() {
        const data = this.result;

        //  store data in database in a text type field
    };

    fileReader.readAsDataURL(file);
}

hen, in the view where I want to download the file, I realize the logic that I commented 母鸡,在我要下载文件的视图中,我意识到我评论的逻辑

General idea works as expected. 一般构想按预期工作。

But I recommend You to keep pdf as file . 但我建议 pdf 保留 为file

Cause Your corrupted pdf issue may be because of db field size (if You keep that string in db) or browser's request url limitations 原因损坏的pdf问题可能是由于db字段大小 (如果将该字符串保留在db中)或浏览器的请求URL 限制引起的

So You're saying : 所以

store data in database in a text type field 在文本类型字段中将数据存储在数据库中

If You don't plan to move to file storage just change field type to: LONGBLOB 如果您不打算移至文件存储,只需字段类型 更改为: LONGBLOB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM