在現在的網頁開發中,在用戶上傳圖片時,一般都會在用戶提供一下預覽功能,html5的FileReader()可以直接用我們實現預覽,而不用先上傳到后台再實現預覽,同時結合canvas可以讓我們輕松的實現壓縮圖片
以下是核心代碼
function readFile(obj) {
var file = obj.target.files[0];
if (!file) {
return;
}
// 判斷類型是不是圖片
if (!/image\/\w+/.test(file.type)) {
hint("請確保文件為圖像類型");
return false;
}
if (Math.floor(file.size / 1024) > 1024 * 10) {
hint("上傳的圖片不得大於10M");
return;
}
// 如果大於2m的圖片就進行壓縮
shouldCompress = 0;
if (Math.floor(file.size / 1024) > 1024 * 2) {
shouldCompress = 1;
}
uiLoading.show();提示開始上傳
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {這里的邏輯可以自定義,例如獲取圖片后放到哪里,增加刪除操作等
var imageData = this.result;
var eDiv = document.createElement("div");
eDiv.className = 'photo-view';
var removeBtn = document.createElement('i');//這里創建刪除圖片的標簽
removeBtn.className = 'removeBtn';
removeBtn.setAttribute('data-index', target);
eDiv.appendChild(removeBtn);
var img = document.createElement('img');
img.src = imageData;
eDiv.appendChild(img);
var eDiv1 = document.createElement("div"),
eDiv2 = document.createElement("div");
eDiv1.className = "wrap-pic";
eDiv2.className = "span6";
eDiv1.appendChild(eDiv);
eDiv2.appendChild(eDiv1);
$productPhoto.parents('.span6').before(eDiv2);
/* 壓縮圖片 */
compressImg(imageData, (shouldCompress == 1 ? 0.3 : 0.7));
}
reader.onloadend = function() {
uiLoading.stop();//清除上傳提示
}
};
function compressImg(src, percent) {
var begintime = new Date().getTime();
var percent = percent || 0.7;
var oImg = new Image();
oImg.src = src;
oImg.onload = function() {
oCanvas.width = this.width;
oCanvas.height = this.height;
oCtx.clearRect(0, 0, this.width, this.height);
oCtx.drawImage(oImg, 0, 0);
var img = oCanvas.toDataURL('image/jpeg', percent).split('base64,')[1];
projectUrl.push(img);這里把base64保存起來傳給后台
}
}
$productPhoto.on("change", function(e) {
readFile(e);
$(this).val(''); //清除獲取的值,為了可以連續上傳同一張
})
參考鏈接:
https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
http://www.zhangxinxu.com/wordpress/2017/07/html5-canvas-image-compress-upload/