<!DOCTYPE html > <html > <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>图片上传本地预览,获得图片的base64(可压缩)</title> <style type="text/css"> .upload_image { width: 800px; } </style> <script type="text/javascript" src="jquery.min.js"></script> </head> <body> <div id="preview"> <img id="imghead" width=200 height=200 border=0 src=‘‘> </div> <canvas id="uploadImg" hidden></canvas> <input type="file" id="fileUp" multiple hidden /> <label for="fileUp">点击上传图片</label> <button id=‘sub‘>提交</button> <script type="text/javascript"> var imgUpload = { imgBase64Arr: [], html : ‘‘, onSelect: function(files) { var i =0; $("#preview").html(‘<div class="upload_loading"></div>‘); var funAppendImage = function() { file = files.files[i]; if (file) { var reader = new FileReader() reader.onload = function(e) { imgUpload.html = imgUpload.html + ‘<div id="uploadList_‘ + i + ‘" class="upload_append_list"><p class="img-outbox"><strong>‘ + file.name + ‘</strong>‘ + ‘<a href="javascript:" class="upload_delete" title="删除" data-index="‘ + i + ‘">删除</a><br />‘ + ‘<img id="uploadImage_‘ + i + ‘" src="‘ + e.target.result + ‘" class="upload_image" /></p>‘ + ‘<span id="uploadProgress_‘ + i + ‘" class="upload_progress"></span>‘ + ‘</div>‘; i++; funAppendImage(); } reader.readAsDataURL(file); } else { $("#preview").html(imgUpload.html); $(".upload_delete").click(function(){ imgUpload.funDelteimg($(this).parents(".img-outbox")); // console.log(files.files[parseInt($(this).attr("data-index"))]) // imgUpload.funDelteimg(files.files[parseInt($(this).attr("data-index"))]); } ) } }; funAppendImage(); }, funDelteimg: function(_this){ console.log(_this) $(_this).remove();//只能删除dom,无法删除内存中的files.files }, funCanvas : function(width, height, ratio, file){//重新绘制图片,获得img的base64 var canvas = document.getElementById("uploadImg"); var cxt = canvas.getContext(‘2d‘); canvas.width = width; canvas.height = height; var img = new Image(); img.src = file; cxt.drawImage(img, 0, 0, width, height); var imgBase = canvas.toDataURL("image/jpeg", ratio); imgUpload.imgBase64Arr.push(imgBase); return imgUpload.imgBase64Arr; }, } //文件上传 $("#fileUp").change(function(){ imgUpload.onSelect(this) }) //获得所有img的 src,可以传给后端 $("#sub").click(function(){ var getBase = $(".upload_image"); getBase.each(function(){//重新绘制图片,减小base64字符串的长度 imgUpload.funCanvas(640, 400, 0.6, $(this).attr("src")); }) console.log(imgUpload.imgBase64Arr) }) </script> </body> </html>
这里图片上传的思路:获得上传后的img,将file的img 转成base64 ,作为前端预览,也可以将base64的字符串,传到后端,由后端生成图片,在传到后端前,可以将其base64的字符串压缩一下,这里的采取的一个方法就是用canvas的重新绘制图片,然后在canvas里就会有 新的base64字符串。
时间: 2024-12-10 17:12:33