lahiruk93
lahiruk93

Reputation: 69

Download content from Base64 source using JS

I have Base64 stream and i wanted to download content as a file from that. I have tried below script.

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

As per above code we have to specify the file type as well. But i wanted to get the file type from the 64 bit stream and download file as it is without hard coding file type because base64 stream could me pdf or docx in my case. Any suggestions?

Upvotes: 0

Views: 739

Answers (2)

Bravo
Bravo

Reputation: 6264

The content of a PDF file always begins with the string %PDF

in base64 this is JVBERi

So, you can inspect the first 6 characters of your base64 for JVBERi - if it matches, it's PDF, if it doesn't it's not PDF

Upvotes: 3

Tuckbros
Tuckbros

Reputation: 437

the mime type is not mandatory in the data uri. so you can just omit it. but all the same, i guess you have to deal with the download filename so you should be able to deal with the appropriate mime type the same way.

Upvotes: -1

Related Questions