base64字符串实现下载文件
Posted phermis
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了base64字符串实现下载文件相关的知识,希望对你有一定的参考价值。
思路:动态创建a标签,将base64字符串地址赋值给href;执行a标签的click事件
let Base64String = data.Base64String;//后端返回的base64字符串 let fileName = "考勤表";//下载的文件名称 let prefix = ‘data:application/vnd.ms-excel;base64,‘ let a= document.createElement(‘a‘);//创建a标签 let content =prefix +Base64String; a.setAttribute(‘href‘,content); a.setAttribute(‘download‘,fileName); a.setAttribute(‘target‘, ‘_blank‘);//打开一个新的窗口 a.setAttribute(‘id‘,"downLoad"); if(document.getElementById(‘downLoad‘)) { document.body.removeChild(document.getElementById(‘downLoad‘)); } document.body.appendChild(a); a.click();
后台有时返回的数据只有base64字符串,需要自己拼接HTTP Content-type的类型;如上面的prefix
下面贴上一段base64字符串:
data:application/vnd.ms-excel;base64,UEsDBBQACAAIABGns07kSK2vGAEAADMDAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbLWSz0oDMRDGX2XJVZq0HkSk2x6qHlWwPsCYzHZD84/MtLZvbzYrIqWCHnqaJN/M9/0IM18evGv2mMnG0IqZnIoGg47Ghk0r3taPk1vREEMw4GLAVhyRxHIxXx8TUlNmA7WiZ053SpHu0QPJmDAUpYvZA5dr3qgEegsbVNfT6Y3SMTAGnvDgIRbze+xg57hZje+DdSsgJWc1cMFSxUw0D4cijpTDXf1hbh/MCczkC0RmdLWHepvo6jSgqDQkPJePydbgvyJi11mNJuqdLyOSUkYw1COyd7JW6cGGMfQFMj+BL67q4NRHzNv3GLeyahcBGCLq+bf8KpKqZXZBEOKjQzpHMSqXjO4ho3nlXJb8PMHPhm8QVZd+8QlQSwcI5EitrxgBAAAzAwAAUEsDBBQACAAIABGns06Y2uuLrgAAACcBAAALAAAAX3JlbHMvLnJlbHONz8EOgjAMBuBXWXqXgQdjDIOLMeFq8AHmVgYB1mWbCm/vjmI8eGz69/vTsl7miT3Rh4GsgCLLgaFVpAdrBNzay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9fcmVscy93b3JrYm9vay54bWwucmVsc1BLAQItABQACAAIABGns07ETz1n2QUAAPQ6AAAYAAAAAAAAAAAAAAAAAIMEAAB4bC93b3Jrc2hlZXRzL3NoZWV0MS54bWxQSwECLQAUAAgACAARp7NOVGfD910BAADiAgAADQAAAAAAAAAAAAAAAACiCgAAeGwvc3R5bGVzLnhtbFBLAQItABQACAAIABGns076RkJZLAEAAFgCAAAUAAAAAAAAAAAAAAAAADoMAAB4bC9zaGFyZWRTdHJpbmdzLnhtbFBLBQYAAAAABwAHAMIBAACoDQAAAAA=
以上是关于base64字符串实现下载文件的主要内容,如果未能解决你的问题,请参考以下文章
如何将音频 base64 字符串下载为 mp3 文件而不损坏它?
下载图像,序列化为 base-64 字符串,转换为 ImageSource
如何在javascript中将PDF文件转换为base64字符串