最近的项目都有拍照上传的功能,所以把这个功能单独抽出来总结积累一下,以便以后复用。
功能:图片选取,滑动预览,删除,异步上传(压缩)
工具:Swiper插件
代码:https://github.com/jackLeong/imagePicker
图片压缩上传代码:
function send(){
var url_send = "http://......";
var scale = 3; //缩放比例
$('.forIndex img').each(function(index,ele){
var canvas = document.createElement("canvas");
var image = this;
var w = image.naturalWidth;
var h = image.naturalHeight
canvas.width = w/scale;
canvas.height = h/scale;
// 坐标(0,0) 表示从此处开始绘制,相当于偏移。
canvas.getContext("2d").drawImage(image,0,0,w,h,0,0,w/scale,h/scale);
var dataURL = canvas.toDataURL("image/png");
var blob = convertBase64UrlToBlob(dataURL);
var file = new File([blob],(new Date()).valueOf()+'.png',{type:"image/png"});
var formData = new FormData();
formData.append('imgData',file);
$.ajax({
url: url_send,
type: 'POST',
data: formData,
cache: false,
async:true,
processData: false,
contentType: false,
success: function (data) {
},
error: function () {
}
});
});
}
function convertBase64UrlToBlob(urlData){
var decoded=window.atob(urlData.split(',')[1]); //去掉Data URL的头部信息,window.atob解码base64,返回字符串(unicode字符串)对象
debugger;
console.log(decoded);
var typedArr = new ArrayBuffer(decoded.length); //开辟字节数大小为decoded.length的类型化数组,相当一片内存空间
var uint8Arr = new Uint8Array(typedArr); //创建一个指向typedArr的Uint8视图
for(var i=0;i<decoded.length;i++){
uint8Arr[i] = decoded.charCodeAt(i); //charCodeAt返回unicode字符编码, uint8Arr,typeArr指向同一地址,
}
return new Blob( [uint8Arr] , {type : 'image/png'});
}
效果: