简体   繁体   中英

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?

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

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.

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