简体   繁体   中英

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.

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.

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.

Update

I am encode the pdf file as follows

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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