JS压缩多个Base64图片为ZIP文件下载

 1、下载函数

		downLoadPic(){
			this.createZipFile().then((blob)=>this.downloadFile1(blob));

		},

2、将解析的数据压缩,

//ele.content未解析的图片数据,ele.name图片名称
//base64ToBlob 图片解析函数
createZipFile(){
    const zip = new JSZip();
	this.picList.forEach(ele=>{
	    const blob = this.base64ToBlob(ele.content);
		zip.file(ele.name +".png", blob , { binary: true });
	});
	return zip.generateAsync({ type: 'blob' });
}

3、压缩后下载函数

		downloadFile(content) {
			let aLink = document.createElement('a');
			let evt = document.createEvent("HTMLEvents");
			evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
			aLink.download = util.getNowTime()+".zip";
			let binaryData = [];
			binaryData.push(content);
			aLink.href = window.URL.createObjectURL(new Blob(binaryData));
			aLink.click();
		},

4、解析Base64图片函数,将Base64数据转换为Uint8Array

		base64ToBlob(code) {
			let parts = code.split(';base64,');
			let contentType = parts[0].split(':')[1];
			let raw = window.atob(parts[1]);
			let rawLength = raw.length;
			let uInt8Array = new Uint8Array(rawLength);
			for (let i = 0; i < rawLength; ++i) {
				uInt8Array[i] = raw.charCodeAt(i);
			}
			return new Blob([uInt8Array], {
				type: contentType
			});
		}

5、时间工具函数

util.getNowTime =  function  () {
	let now = new Date();
	let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
	let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
	let today = now.getDate(); //获取当前日(1-31)
	let hour = now.getHours(); //获取当前小时数(0-23)
	let minute = now.getMinutes(); //获取当前分钟数(0-59)
	let second = now.getSeconds(); //获取当前秒数(0-59)
	let nowTime = ''
	nowTime = year + '-' + fillZero(month) + '-' + fillZero(today) + '-' + fillZero(hour) + '-' +
		fillZero(minute) + '-' + fillZero(second)
	return nowTime
}
function fillZero (str) {
	let realNum;
	if (str < 10) {
		realNum = '0' + str;
	} else {
		realNum = str;
	}
	return realNum;
}

你可能感兴趣的:(javascript,前端)