当前位置: 代码迷 >> 综合 >> js将文件处理成base64
  详细解决方案

js将文件处理成base64

热度:92   发布时间:2024-01-16 23:34:02.0

1.如果是中英文处理成base64

   可以使用jquery.base64.js,里面封装了加密和解密方法,直接调用即可,方便可用

2如果是图片处理成base64

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><script type="text/javascript" src="js/jquery.min.js"></script></head><body><input id="file" type="file" capture="microphone" accept="image/*"><img id="img" alt="123" /></body><script>$("#file").change(function() {var m_this = this;cutImageBase64(m_this, null, 400, 0.8);})//将base64转换为blob//调用function cutImageBase64(m_this, id, wid, quality) {var file = m_this.files[0];var URL = window.URL || window.webkitURL;var blob = URL.createObjectURL(file);var base64;var img = new Image();img.src = blob;img.onload = function() {var that = this;//生成比例var w = that.width,h = that.height,scale = w / h;w = wid || w;h = w / scale;//生成canvasvar canvas = document.createElement('canvas');var ctx = canvas.getContext('2d');$(canvas).attr({width: w,height: h});ctx.drawImage(that, 0, 0, w, h);// 生成base64            base64 = canvas.toDataURL('image/png', quality || 0.8);console.log(base64); //此处是转化的base64,可直接加载到img标签的src$("#img").attr("src", base64);var blob = dataURLtoBlob(base64);var file = blobToFile(blob, "a1.png");console.log(file);//var json = eval('(' + file + ')');//$("#img").attr("src", file);};}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});}//将blob转换为filefunction blobToFile(theBlob, fileName) {theBlob.lastModifiedDate = new Date();theBlob.name = fileName;return theBlob.name;}</script>
</html>