1.取到file文件。
2.将图片压缩
function processfile(file) { var reader = new FileReader(); reader.onload = function (event) { var blob = new Blob([event.target.result]); window.URL = window.URL || window.webkitURL; var blobURL = window.URL.createObjectURL(blob); var image = new Image(); image.src = blobURL; image.onload = function() { var dataUrl= canvasImg(image);//利用画布将文件转换为 返回的是一串Base64编码的URL uploadFile(resized);//删除服务器 } }; reader.readAsArrayBuffer(file); } function canvasImg(img) { //压缩的大小 var max_width =500; var max_height =500; var canvas = document.createElement('canvas'); var width = img.width; var height = img.height; if(width > height) { if(width > max_width) { height = Math.round(height *= max_width / width); width = max_width; } } else{ if(height > max_height) { width = Math.round(width *= max_height / height); height = max_height; } } canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, width, height); //压缩率 return canvas.toDataURL("image/jpeg",0.9); }
3.上传到服务器
//将dataUrl转换为二进制流
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}); } function uploadFile(dataUrl){ var file = dataUrlToBlob(dataUrl);//转换为流 var fd = new FormData();//formdata格式上传服务器 fd.append("file",file); $.ajax({ type: 'POST', url: "url", data: fd, processData: false, async: true, contentType: false, dataType: 'json', success: function (data) { } }); }