<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1"> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div> <h4>file 文件转成 base64 字符</h4> <input type="file" id="file"/> <img src="" id="portrait" style="width:100px; height:100px; display: block;" /> <textarea id="base64Textarea" cols="30" rows="10" placeholder="base64信息输出"></textarea> </div> <br> <br> <br> < div > < h4 > Convert base64 characters to blob objects </ h4 > < button id = "toBlob" > Click to convert to blob objects </ button > < p > Convert to blob objects for convenience and upload to Qiniu </ p > </ div > <script> var base64Data = '' ; var blob = null ; document.getElementById('file').onchange=function(e){ var file = e.target.files[0]; if(window.FileReader) { var fr = new FileReader(); fr.readAsDataURL(file); fr.onloadend = function(e) { base64Data = e.target.result; document.getElementById('portrait').src = base64Data; document.getElementById('base64Textarea').value = base64Data; } } } // The first way to convert to blob object function dataURLtoBlob(dataurl) { var arr = dataurl.split( ' , ' ), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], {type:mime}); } document.getElementById('toBlob').onclick=function(){ if ( base64Data ) { blob = dataURLtoBlob(base64Data); console.log(blob); alert( ' It has been converted into a blob object, please check the browser console ' ); }else{ alert( ' You haven't generated the base64 file ' ); } } </script> </body> </html>