<!DOCTYPE html> <html> <head> <title>Covert Base64 string to file</title> <style type="text/css"> #base64InputTextArea { width: 600px; height: 200px; } .msgInput { width: 300px; display:block } </style> </head> <body> <h1>将Base64字符串转换成文件</h1> <textarea id="base64InputTextArea" placeholder="请输入base64字符串"></textarea> <br> <input type="text" id="typeInput" class="msgInput" placeholder="输入类型,如:数据:音频/ mp3"> <br> <input type="text" id="fileNameInput" class="msgInput" placeholder="输入下载名称,如:1. mp3"> <br> <button onclick="covertBase64ToFile()">隐藏base64字符串到文件</button> <br> <br> <a href="" id ="downloadButton">下载文件</a> <script type="text/javascript"> function base64ToArrayBuffer(base64) { var binaryString = window.atob(base64) var length = binaryString.length var bytes = new Uint8Array(length) for (var i = 0; i < length; i++) { bytes[i] = binaryString.charCodeAt(i) } return bytes.buffer } function addDownloadContent(text, name, type) { var downloadButton = document.getElementById("downloadButton"); var file = new Blob([text], {type: type}); downloadButton.href = URL.createObjectURL(file); downloadButton.download = name; } function covertBase64ToFile() { var textArea = document.getElementById("base64InputTextArea") var base64String = textArea.value if (base64String.length <= 0) { alert("please input base64 string") return false } var typeInput = document.getElementById("typeInput") var type = typeInput.value if (type.length <= 0) { alert("please input data type") return false } var fileNameInput = document.getElementById("fileNameInput") var fileName = fileNameInput.value if (fileName.length <= 0) { alert("please input file name") return false } var bytes = base64ToArrayBuffer(base64String) console.log(bytes) addDownloadContent(bytes, fileName, typeInput) return true } </script> </body> </html>
评论已关闭!