上传5MB多的图片,保存本地缓存时,提示存储数据超出配额,如下异常:
settings_save(o,event) is null. DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'goods_print_settings_4' exceeded the quota.

用的是 chrome,查了下资料
What is the max size of localStorage values?
https://www.geeksforgeeks.org/what-is-the-max-size-of-localstorage-values/
运行下面代码,我当前使用的 chrome 最大存储为 5MB。

<div> 
	localStorage limit in your Browser is 
	<span id="size">...</span> KBs. 
</div> 
<script> 
//this script is to find the size of localStorage 
function func1(num) { 
	return new Array((num * 1024) + 1).join('a') 
}
	
// Determine the size of localStorage if it's not set 
if (!localStorage.getItem('size')) { 
	var i = 0; 
	try { 
		// Test up to 10 MB 
		for (i = 0; i <= 10000; i += 250) { 
			localStorage.setItem('test', func1(i)); 
		} 
	} catch (e) { 
		localStorage.removeItem('test'); 
		localStorage.setItem('size', i ? i - 250 : 0); 
	} 
}
		
// when window is loaded this function is 
// called and the size of localStorage is calculated 
window.onload = function calculate(){ 
	var el = document.getElementById('size');	 
	el.innerHTML = localStorage.getItem('size'); 
}
</script>

于是将上传图片进行压缩处理。

function file_chagne(sef) {
	var file = sef.files[0], reader = new FileReader(), imgElm = $$('#logosrc');
	if (file.size > 102400) {
		if (!confirm('当前LOGO图片'+getFileSize(file.size)+',过大图片压缩后可能会影响清晰度。\n建议LOGO不大于100KB,是否继续上传?'));
		return;
	}

	reader.onload = function(e) {
		if (file.size > 102400) {
			resizeImage(base64);
		} else {
			showImage(e.target.result);
		}
	}
	reader.readAsDataURL(file);
}
function resizeImage(base64) {
	var img = new Image(), maxWidth = 120, maxHeight = maxWidth; // 图片尺寸最大 120px
	img.src = base64;
	img.onload = function () {
		var ig = new Image(), offsetX = 0, offsetY = 0;
		ig.src = this.src;
		
		// 仅限制图片宽度,忽略高度
		if (ig.width > maxWidth) {
			var obj = rescaleImageSize(ig.width, ig.height, maxWidth, maxHeight);
			maxWidth = obj.width;
			maxHeight = obj.height;
			offsetX = Math.round((Math.round(maxWidth)-maxWidth)/2); // 开始剪切的 x 坐标位置
		} else {
			maxWidth = ig.width;
			maxHeight = ig.height;
			offsetY = Math.round((Math.round(maxHeight) - maxHeight)/2); // 开始剪切的 y 坐标位置
		}

		var c = document.createElement('canvas'), ctx = c.getContext('2d');
		c.width = maxWidth;
		c.height = maxHeight;
		
		/******* 开始在画布上绘制图片 *******
		*	context.drawImage(img, sx, sy, swidth, sheight, x, y, width, height);
		*	offsetX:	开始剪切的 x 坐标位置
		*	offsetX: 	开始剪切的 y 坐标位置
		*	maxWidth:	被剪切图像的宽度
		*	maxHeight:	被剪切图像的高度
		*************************************/
		ctx.drawImage(this, offsetX, offsetY, maxWidth, maxHeight);
		showImage(c.toDataURL(file.type));
	}
}

更多推荐